2012-12-21 75 views
4

我有一系列的持续时间,如“118:34:42”,其中118是小时,34是分钟,42是秒的格式,范围长达118小时。输出应该是几秒钟。工作持续时间超过24小时在R

我想将它转换为R中的某种时间类型,但我查看过的大多数库都想添加日期(lubridate,zoo,xts),或返回“NA”,这是由于小时超过了24小时的范围。我可以解析字符串并返回几秒钟,但我想知道是否有更快的方法。

我稍微有点新R(可能与此合作3个月)。

任何帮助搞清楚如何处理这将不胜感激。

实施例:

library(lubridate) 
    x <- c("118:34:42", "114:12:12") 
    tt <- hms(x) 
    Error in parse_date_time(hms, orders, truncated = truncated, quiet = TRUE) : 
    No formats could be infered from the training set. 
    #try another route 
    w <- "118:34:42" 
    tt2 <- hms(w) 
    tt2 
    #[1] NA 
    z <- "7:02:02" 
    tt3 <- hmw(z) 
    tt3 
    #[1] "7H 2M 2S" 
+0

您可以将时间转换为秒:'library(gsubfn); secs < - c(strapply(x,“\\ d +”,as.numeric)%*%c(3600,60,1))'然后在几秒钟内完成所有处理。要转换回来:'sprintf(“%d:%02d:%02d”,secs%/%3600,secs%/%60 %% 60,secs %% 60) –

回答

5

lubridate包有一个函数hms()返回一个时间对象:

library(lubridate) 

x <- c("118:34:42", "114:12:12") 
tt <- hms(x) 

tt 
[1] 118 hours, 34 minutes and 42 seconds 
[2] 114 hours, 12 minutes and 12 seconds 

hms()返回Period类的一个对象的函数:

str(tt) 
Formal class 'Period' [package "lubridate"] with 6 slots 
    [email protected] .Data : num [1:2] 42 12 
    [email protected] year : num [1:2] 0 0 
    [email protected] month : num [1:2] 0 0 
    [email protected] day : num [1:2] 0 0 
    [email protected] hour : num [1:2] 118 114 
    [email protected] minute: num [1:2] 34 12 

您可以使用这些对象进行算术运算。例如:

tt[2] - tt[1] 
[1] -4 hours, -22 minutes and -30 seconds 
+0

我仍然拿到NA。这是我收到的输出:'code'tt < - hms(timecolumn) > head(timecolumn) [1]“115:53:34”“7:13:27”“12:12:55”“ (“tt”) [1] NA“7H 13M 27S”“12H 12M 55S”“3H 28M 35S”“3H 5M 23S” “”10M 30S“'code' – alplv

+0

@alplv为了追踪这个,你必须提供更多关于你的设置的信息,例如R的版本,Lubridate的版本等。 – Andrie

+0

运行Lubridate 1.20,R 2.15.2。我今天早上跑了一些更新,只是为了检查是否有任何软件包过时了。试图现在调试该问题。走过几条路,看看我能否从Lubridate的帮助中找到任何东西。感谢迄今为止的指针。 – alplv

相关问题