将时间拆分为带前导零和分钟的小时

Split Time into hours with leading zero and minutes

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

dateorder <- structure(list(Date = c("30/04/2021", "30/04/2021", "30/04/2021", "30/04/2021", "30 /04/2021", "30/04/2021", "30/04/2021", "30/04/2021", "30/04/2021", "30/04/2021"), 时间 = c (0L, 100L, 200L, 300L, 400L, 500L, 600L, 700L, 800L, 900L), 降雨量 = c(0.4, 0.4, 0.6, 0.8, 0.8, 1, 0, 0, 0, 0), Date_Formatted = 结构 (c(18747, 18747, 18747, 18747, 18747, 18747, 18747, 18747, 18747, 18747), class = "日期"), 强度 = c(0.4, 0, 0.2, 0.2 , 0, 0.2, -1, 0, 0, 0)), row.names = c(NA, 10L), class = "data.frame") sub("(\d{2})(\d{2})", "\1:\2",sprintf("%04d", dateorder$Time)) str_sub(日期顺序$Time2,1,2) substr(dateorder$Time2,start = 1, stop = 2)

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

首先使用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)。

基础 R 选项 -

  • sprintf 如果 Time 列中的数字少于 4 位,则添加 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})')