我需要将%H:%M:%S (类=因子)格式的时间间隔转换为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()中包含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"任何帮助都将不胜感激!
发布于 2017-05-12 19:05:07
您可以首先将数据格式更改为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。
v=as.difftime(unlist(v),unit="secs")https://stackoverflow.com/questions/43944426
复制相似问题