Frage

I’m trying to solve a problem that at the beginning looked very simple but I've found myself stuck. So, I have an object that is character called “out”:

out<-c( " 59mn 59s", " 59mn 59s", " 1h 0mn",  " 1h 0mn",  " 1h 0mn",  " 1h 0mn",  " 1h 0mn", " 1h 0mn",   " 59mn 59s"," 59mn 59s", " 46mn 42s")

My final goal is to use the function “hms” from the package lubridate to convert the character into time object. The problem is that the data set is not consistent and in some cases I have hours and minutes others I have minutes and seconds. So I made an attempt to uniform the data set like this:

    out<-for(p in 1:length(out)) {                                         
 ifelse(!grepl("h",out[p]),paste("0h",out[p]),ifelse(!grepl("mn",out[p]),paste("0h 0mn",out[p]),ifelse(!grepl("s",out[p]),paste(out[p],"0s"))))                                                
                           } 

The ifelse statement by itself works fine however in a for loop it just returns NULL. Does anyone have an idea of what is going wrong in this code? Another option would be a combination of the functions “hm” and “hms” from lubridate but my are skills won’t allow me to go on that path.

Many thanks

War es hilfreich?

Lösung

Since ifelse is vectorised, you can do this without using a loop:

ifelse(!grepl("h",out), paste("0h",out),
       ifelse(!grepl("mn",out), paste("0h 0mn",out),
              ifelse(!grepl("s",out), paste(out,"0s"), NA)))

#[1] "0h  59mn 59s" "0h  59mn 59s" " 1h 0mn 0s"   " 1h 0mn 0s"   " 1h 0mn 0s"   " 1h 0mn 0s"   " 1h 0mn 0s"  
#[8] " 1h 0mn 0s"   "0h  59mn 59s" "0h  59mn 59s" "0h  46mn 42s"

Is that what you expected?

(Note that I added an NA incase all others conditions are not TRUE and replaced out[p] inside the ifelse with only out.)

Andere Tipps

Using some safer regular expression.

t<-c( " 59mn 59s", " 59mn 59s", " 1h 0mn",  " 1h 0mn",  " 1h 0mn",  " 1h 0mn",  " 1h 0mn", " 1h 0mn",   " 59mn 59s"," 59mn 59s", " 46mn 42s")
t[grep(" [0-9]{2}mn", t)] = paste( "0h", t[grep(" [0-9]{2}mn", t)], sep="")
t[grep("mn$", t)] = paste(t[grep("mn$", t)], " 0s", sep ="")

hms(t)
> [1] "59M 59S"  "59M 59S"  "1H 0M 0S" "1H 0M 0S" "1H 0M 0S" "1H 0M 0S" "1H 0M 0S"
> [8] "1H 0M 0S" "59M 59S"  "59M 59S"  "46M 42S" 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top