Home > Enterprise >  Is there a way of converting four-digit numbers to time values in r?
Is there a way of converting four-digit numbers to time values in r?

Time:11-07

there is probably a very simple solution to this problem, but when I try using as.POSIXlt or strptime I keep getting a single value of 'NA' as a result.

What I need to do is transform 3 and 4 digit numbers e.g. 2300 or 115 to 23:00 or 01:15 respectively, but I simply cannot get any code to work.

Any advice would be greatly appreciate. Thank you.

EDIT

Basically, this data fame of outputs:

Time
1   2345
2   2300
3   2130
4   2400
5    115
6   2330
7    100
8   2300
9   1530
10   130
11   100
12   215
13  2245
14   145
15  2330
16  2400
17  2300
18  2230
19  2130
20    30

should look like this:

Time
    1   23:45
    2   23:00
    3   21:30
    4   24:00
    5   01:15
    6   23:30
    7   01:00
    8   23:00
    9   15:30
    10  01:30
    11  01:00
    12  02:15
    13  22:45
    14  01:45
    15  23:30
    16  24:00
    17  23:00
    18  22:30
    19  21:30
    20  00:30

CodePudding user response:

I think you can use the following solution. However this is actually producing a character vector:

gsub("(\\d{2})(\\d{2})", "\\1:\\2", sprintf("d", df$Time)) |>
  as.data.frame() |>
  setNames("Time") |>
  head()

   Time
1 23:45
2 23:00
3 21:30
4 24:00
5 01:15
6 23:30
  •  Tags:  
  • r
  • Related