【问题标题】:Split Time into hours with leading zero and minutes将时间拆分为带有前导零和分钟的小时
【发布时间】:2022-01-21 09:35:23
【问题描述】:

如何在下面的数据集中将时间拆分为小时,前导零和分钟。我用 sprintf 尝试了 sub 但没有奏效。还尝试了 str_sub 和 substr 但无法获得所需的输出。谢谢。

日期顺序

# Expected output
# Hr mm
# 00 00
# 01 00
# 02 00

【问题讨论】:

  • 能否在问题中包含预期的结果?
  • 在您调用 sub 尝试 dateorder$Time 使用大写 T
  • @Peter - 感谢您指出错字。这在一定程度上有所帮助。我想将时间列拆分为“小时”和“分钟”,在 0 到 9 小时之间的时间前在小时前加上前导零。示例 00, 01, 02,...09, 10, 11 小时和分钟双零。
  • 感谢您的帮助,请您编辑问题中的数据,以包含一些包含这些案例的时间列示例,以便测试和验证可能的解决方案。
  • @Peter - 感谢为清晰而编辑。

标签: r time


【解决方案1】:

首先使用strptime/strftime,然后使用strsplit

tm <- strptime(paste(Sys.Date(), dateorder$Time), '%F %H%M') |> 
  strftime('%H:%M')
# [1] "10:00" "11:00" "12:00" "13:00" "14:00" "15:00" "16:00" "17:00" "18:00" "19:00"

cbind(dateorder, tm=do.call(rbind, strsplit(tm, ':')))
#           Date Time Rainfall Date_Formatted Intensity tm.1 tm.2
# 1  30/04/2021 1000      0.4     2021-04-30       0.4   10   00
# 2  30/04/2021 1100      0.4     2021-04-30       0.0   11   00
# 3  30/04/2021 1200      0.6     2021-04-30       0.2   12   00
# 4  30/04/2021 1300      0.8     2021-04-30       0.2   13   00
# 5  30/04/2021 1400      0.8     2021-04-30       0.0   14   00
# 6  30/04/2021 1500      1.0     2021-04-30       0.2   15   00
# 7  30/04/2021 1600      0.0     2021-04-30      -1.0   16   00
# 8  30/04/2021 1700      0.0     2021-04-30       0.0   17   00
# 9  30/04/2021 1800      0.0     2021-04-30       0.0   18   00
# 10 30/04/2021 1900      0.0     2021-04-30       0.0   19   00

注意: R 版本 4.1.2 (2021-11-01)。

【讨论】:

  • 谢谢,但是我无法正常工作。 |> 在第一行末尾有什么作用?我也尝试删除它。 strsplit(tm, ":") 中的错误:非字符参数
  • @AravindanKalai 你的R版本好像过时了,能更新一下吗?或者strftime(strptime(paste(Sys.Date(), dateorder$Time), '%F %H%M'), '%H:%M')
【解决方案2】:

基本 R 选项 -

  • 如果Time 列中的位数少于 4,sprintf 会添加 0 作为前缀。
  • strcapture 将前 2 个数字捕获为小时 (hh),将后 2 个数字捕获为分钟 (mm)。
strcapture('(\\d{2})(\\d{2})', sprintf('%04d', dateorder$Time), 
           proto = list(hh = character(), mm = character()))

#   hh mm
#1  00 00
#2  01 00
#3  02 00
#4  03 00
#5  04 00
#6  05 00
#7  06 00
#8  07 00
#9  08 00
#10 09 00

使用tidyverse -

library(tidyverse)

dateorder %>%
  mutate(Time = str_pad(Time, 4, pad = '0')) %>%
  extract(Time, c('hh', 'mm'), '(\\d{2})(\\d{2})')

【讨论】:

  • @Ronal Shah - 我怎样才能让这两个新列与“dateorder”表中的其他列一起获得?
  • 如果您使用第一个选项,您可以 cbind strcapture 输出 dateorder &lt;- cbind(dateorder, strcapture(....)) 。对于第二个选项,只需将输出分配回dateorder,即dateorder &lt;- dateorder %&gt;% mutate(....
  • 感谢@Ronal Shah
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多