简体   繁体   English

有没有办法将四位数字转换为 r 中的时间值?

[英]Is there a way of converting four-digit numbers to time values in r?

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.这个问题可能有一个非常简单的解决方案,但是当我尝试使用 as.POSIXlt 或 strptime 时,结果我一直得到一个 'NA' 值。

What I need to do is transform 3 and 4 digit numbers eg 2300 or 115 to 23:00 or 01:15 respectively, but I simply cannot get any code to work.我需要做的是将 3 位和 4 位数字(例如 2300 或 115)分别转换为 23:00 或 01:15,但我根本无法使用任何代码。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM