Adding seconds to character vector in `R`

Viewed 27

I have a character vector time:

> dput(time)
c("10:00", "10:00", "13:00", "13:00", "", "0.559027778", "0.559027778", 
"0.559027778", "0.559027778", "21:33", "21:33", "", "", "", "", 
"", "10:40", "", "", "", "", "", "15:10", "15:10", "15:17", "", 
"10:30", "", "10:40", "10:40", "10:40", "10:40", "12:40", "", 
"", "", "", "", "", "16:00", "16:00", "12:40", "12:40", "12:30", 
"12:30", "21:00", "21:00", "17:25", "17:25", "18:00", "18:00", 
"17:30", "17:30", "18:00", "", "", "18:00", "", "15:00", "15:00", 
"16:00", "", "", "", "", "18:30:00", "", "", "", "0.541666667", 
"", "", "", "16:50", "", "", "")

Many entries of this vector represent times, with hour and minute, but without seconds. E.g., 12:30, 21:00, or 17:25. I would like to add to this type of values also the information relating to the seconds (00), i.e. 12:30:00, 21:00:00, 17:25:00 and so on. The other entries like, e.g. empty ones or 0.559027778 should remain as they are.

1 Answers

We can convert to Itime and then back to character on those elements having :

library(data.table)
i1 <- grep(":", time)
time[i1] <- as.character(as.ITime(time[i1]))

-output

time
#[1] "10:00:00"    "10:00:00"    "13:00:00"    "13:00:00"    ""            "0.559027778" "0.559027778" "0.559027778" "0.559027778" "21:33:00"    "21:33:00"   
#[12] ""            ""            ""            ""            ""            "10:40:00"    ""            ""            ""            ""            ""           
#[23] "15:10:00"    "15:10:00"    "15:17:00"    ""            "10:30:00"    ""            "10:40:00"    "10:40:00"    "10:40:00"    "10:40:00"    "12:40:00"   
#[34] ""            ""            ""            ""            ""            ""            "16:00:00"    "16:00:00"    "12:40:00"    "12:40:00"    "12:30:00"   
#[45] "12:30:00"    "21:00:00"    "21:00:00"    "17:25:00"    "17:25:00"    "18:00:00"    "18:00:00"    "17:30:00"    "17:30:00"    "18:00:00"    ""           
#[56] ""            "18:00:00"    ""            "15:00:00"    "15:00:00"    "16:00:00"    ""            ""            ""            ""            "18:30:00"   
#[67] ""            ""            ""            "0.541666667" ""            ""            ""            "16:50:00"    ""            ""  
Related