R as.difftime() 时间超过 1 天的问题

R as.difftime() issue for times longer than 1 day

我需要将格式为 %H:%M:%S(class = 因子)的时间间隔转换为 class = difftime。我目前正在使用 as.difftime() 来执行此操作,但是当小时值 > 23 时 returns NA。

TimeElapsed_raw = as.factor(c("03:59:59", "21:00:00", "01:03:46", "44:00:00", "24:59:59"))
TimeElapsed = as.difftime(as.character(TimeElapsed_raw), format = "%H:%M:%S")
TimeElapsed

Time differences in hours
[1]  3.999722 21.000000  1.062778        NA        NA

无论是否在 as.difftime() 中包含格式语句,我都遇到同样的问题:

as.difftime("65:01:17")
Time difference of NA secs

但这行得通:

as.difftime(65.1, units = "hours")
Time difference of 65.1 hours

我也尝试过使用 lubridate as.duration() 函数,但它计算的值似乎没有意义。

as.duration(TimeElapsed_raw)
[1] "2s" "3s" "1s" "5s" "4s"

如有任何帮助,我们将不胜感激!

您可以先将数据格式更改为 xH xM xS,lubridate 中的 duration 函数可以理解该格式:

x=gsub("(^\d{2}):(\d{2}):(\d{2})$","\1H \2M \3S",as.character(TimeElapsed_raw))
[1] "03H 59M 59S" "21H 00M 00S" "01H 03M 46S" "44H 00M 00S" "24H 59M 59S"

然后应用duration:

duration(x)
[1] "14399s (~4 hours)"     "75661s (~21.02 hours)" "3826s (~1.06 hours)"  
[4] "158461s (~1.83 days)"  "89999s (~1.04 days)"  

否则,使用 as.difftime,您可以先将数据拆分为小时、分钟和秒,然后分别将每个数据提供给 as.difftime:

v=lapply(strsplit(TimeElapsed_raw,":"),function(x) {as.difftime(as.numeric(x[1]),units="hours")+as.difftime(as.numeric(x[2]),units="mins")+as.difftime(as.numeric(x[3]),units="secs")})

[[1]]
Time difference of 14399 secs

[[2]]
Time difference of 75600 secs

[[3]]
Time difference of 3826 secs

[[4]]
Time difference of 158400 secs

[[5]]
Time difference of 89999 secs

如果要将列表转换为矢量,请务必在之后将其重新转换为 difftime,因为 unlist 会丢失 class。

v=as.difftime(unlist(v),unit="secs")