How can you insert a colon every two characters?

r

Solution

Since the data is time related, you should consider storing it in a POSIX format:

> df <- data.frame(Time=c("024201", "054722", "213024", "205022", "205024", "125440")
> df$Time <- as.POSIXct(df$Time, format="%H%M%S")
> df

                 Time
1 2014-01-05 02:42:01
2 2014-01-05 05:47:22
3 2014-01-05 21:30:24
4 2014-01-05 20:50:22
5 2014-01-05 20:50:24
6 2014-01-05 12:54:40

To output just the times:

> format(df, "%H:%M:%S")
      Time
1 02:42:01
2 05:47:22
3 21:30:24
4 20:50:22
5 20:50:24
6 12:54:40

Problem

I have a column of time values, except that they are in character format and do not have the colons to separate H, M, S. The column looks similar to the following: ``` Time 024201 054722 213024 205022 205024 125440 ``` I want to convert all the values in the column to look like actual time values in the format `H:M:S`. The values are already in `HMS` format, so it is simply a matter of inserting colons, but that is proving more difficult than I thought. I found a package that adds commas every three digits from the right to make Strings look like currency values, but nothing for time (without also adding a date value, which I do not want to do). Any help would be appreciated.

Original source