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

时间:2017-05-12 18:33:17

标签: r time duration lubridate difftime

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

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()中包含format语句,我都有同样的问题:

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"

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

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

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

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