Search code examples
rtime-format

Insert colons into time stamp hhmmss


i am new to stackoverflow and R programming.

Suppose i have the following data:

time<-as.factor(c(142250,101449,85829))
as.data.frame(time)

This will return the following:

    time
  1 142250
  2 101449
  3  85829

What i want is to convert the above into time stamps with a semicolon for example:

142250 will be 14:22:50

i was able to find the following code using the chron package:

library('chron')
times(gsub("(..)(..)(..)", "\\1:\\2:\\3", date))

which returns

[1] 14:22:50 10:14:49 **<NA>**  

As you can see the problem is if there are less than 6 characters it will return an NA.

The output i am after is to return the following results:

[1] 14:22:50 10:14:49 8:58:29  

I believe i may have to do some sort of looping but i am not sure how to go about it?

Any help will be much appreciated.


Solution

  • So in order to reach your desired output you could use sprintf and add a leading 0 in case the string is shorter than 6, though see @Rolands comment and please provide more clarity

    library('chron')
    time <- sprintf("%06d", as.numeric(as.character(time)))
    times(gsub("(..)(..)(..)", "\\1:\\2:\\3", time))
    ## [1] 14:22:50 10:14:49 08:58:29