2

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

任何帮助,将不胜感激!

4

1 回答 1

1

您可以首先将数据格式更改为 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")
于 2017-05-12T19:05:07.553 回答