如何将文本转换为具有负持续时间的时间?

时间:2015-07-20 12:15:03

标签: r time

我想将c("2:25", "-3:45")转换为格式为"h:m"的时间向量,并获取将返回mean(c("2:25", "-2:25"))的向量"0:0"的平均值。这可能吗?

2 个答案:

答案 0 :(得分:1)

使用lubridate,您可以轻松创建Duration类的对象:

library(lubridate)
x <- c("2:25", "-3:45")
l <- lapply(strsplit(x, ":"), as.numeric)
lst <- lapply(l, function(x) {if(x[1] < 0) x[2] <- x[2]-2*x[2];x})
res <- lapply(lst, function(x) duration(as.numeric(x[1]), "hours")+
         duration(as.numeric(x[2]), "minutes"))
#[[1]]
#[1] "8700s (~2.42 hours)"
#
#[[2]]
#[1] "-13500s (~-3.75 hours)"
duration(mean(unlist(res)), "seconds")
#[1] "-2400s (~-40 minutes)"

第二个例子:

x2 <- c("2:25", "-2:25")
l <- lapply(strsplit(x2, ":"), as.numeric)
lst <- lapply(l, function(x) {if(x[1] < 0) x[2] <- x[2]-2*x[2];x})
res <- lapply(lst, function(x) duration(as.numeric(x[1]), "hours")+
         duration(as.numeric(x[2]), "minutes"))
#[[1]]
#[1] "8700s (~2.42 hours)"
#
#[[2]]
#[1] "-8700s (~-2.42 hours)"
duration(mean(unlist(res)), "seconds")
#[1] "0s"

答案 1 :(得分:0)

&#34;持续时间&#34;来自&#34; lubridate&#34;没有必要。 &#34; difftime&#34;来自&#34; base&#34;足够好了:

x <- c("2:25", "-3:45", "1:11", "-0:03")
A <- abs(matrix(as.numeric(unlist(strsplit(x,":"))),nrow=2))
A[,grep("-",x)] <- -A[,m]

t <- as.difftime(t(A) %*% c(60,1), unit="mins")

结果:

> t
Time differences in mins
     [,1]
[1,]  145
[2,] -225
[3,]   71
[4,]   -3
> mean(t)
Time difference of -3 mins

矩阵的第一行&#34; A&#34;包含小时数,第二行包含分钟数。人们必须暂时忽略&#34; - &#34; -signs,因为它们有效时间 分钟。随后,与负时间对应的列将完全乘以-1。

如果所需的输出格式为&#34; HH:MM&#34;人们可以使用&#34; sprintf&#34;:

mt <- mean(t)

c <- sprintf( "%s%02i:%02.0f",
              ifelse(as.numeric(mt)<0,"-","+"),
              abs(as.numeric(mt)) %/% 60,
              abs(as.numeric(mt)) %% 60 )

结果:

> c
[1] "-00:03"