How to programmatically ad a character to a string in R

82 Views Asked by At

I apologize in advance if this has been posted elsewhere. I am new to R, and I am having trouble manipulating a dataframe.

I have a column in my dataframe that contains times in the format of hh mm ss. However, some values only have a single "0" in the hh place (for example, "0:01:30" or "0:20:30").

I am trying to use the chron package to convert these into a time object so that I can find the min, max, and mean time durations, but I need to add a zero to the hours column before I do so. What would be the best way to do this in R? Since some values in the column don't need to have a zero added, what would be the best way to iterate through each value and check for a specific condition?

Thanks in advance for your help!

1

There are 1 best solutions below

0
On

Probably you can deal with that directly via the chron package as suggested in the comments.

Otherwise a simple if else statement should do the job. Assuming t is your column and dat your dataframe, and the issue happens only in the hh part(otherwise add more conditions):

library(dplyr)
dat$t1 <- if_else(nchar(dat$t)==7, paste0(0,dat$t), dat$t)