1

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.

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
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • 1
    Is this a question about *formatting* or type *conversion*? In other words, do you simple want to reformat "2345" as "23:45"? Or do you need to convert a `character` vector into an e.g. `POSIXct` vector. – Maurits Evers Nov 07 '21 at 01:15
  • @Michael To convert your data to a dedicated time class, see [Convert hour:minute:second (HH:MM:SS) string to proper time class](https://stackoverflow.com/questions/12034424/convert-hourminutesecond-hhmmss-string-to-proper-time-class) – Henrik Nov 08 '21 at 14:34
  • Please do not vandalise your own post when it has received an answer - there's a reason why you cannot delete it. – user438383 Nov 29 '21 at 11:45

1 Answers1

1

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

gsub("(\\d{2})(\\d{2})", "\\1:\\2", sprintf("%04d", 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
Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
  • Is this the answer you were looking for? It's just character vector. I don't think you could turn a numeric into time without date! and with regard to your question could you elaborate more? – Anoushiravan R Nov 07 '21 at 01:29
  • I am so sorry I just don't understand your point. Could you please put it here and I will take a look at it asap. Or possibly ask a new question. – Anoushiravan R Nov 07 '21 at 01:36