0

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

PatraoPedro
  • 197
  • 1
  • 16
  • beginner has a good answer, but if you would not save the results of your for loop and instead print each iteration, you would see what was going on – rawr Jul 30 '14 at 13:25
  • If you want to uniform your data you might want to remove the leading space or the last space present in some strings. ( http://stackoverflow.com/q/10502787/2886003 might be helpful) – llrs Jul 30 '14 at 14:24

2 Answers2

2

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.)

talat
  • 68,970
  • 21
  • 126
  • 157
2

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" 
Vlo
  • 3,168
  • 13
  • 27
  • It does add the hours. You are looking at `hms(t)` instead of `t` – Vlo Jul 30 '14 at 15:10
  • True, ha. I've been making a point to learn perl's ridiculous regex, so I like answers that use any regular expressions. +1 – rawr Jul 30 '14 at 21:07