2015-07-20 23 views

回答

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" 
0

從 「lubridate」, 「時間」 是不是真的有必要。 「difftime」從「基」是不夠好:

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 

矩陣的第一行的「A」包含小時,第二行的分鐘。人們必須暫時忽略「 - 」 - 標誌,因爲它們的有效期爲數小時 分鐘。隨後,對應於負時間的列完全乘以-1。

如果所需的輸出格式是 「HH:MM」 可以使用 「的sprintf」:

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" 
相關問題