是否有一个良好的方式来处理时间时期,如05:30(5分钟,30秒)在R?

或者什么是最快的方式将其转换成一个整数几秒钟?

我只能转换的日期,并不能真的找到一个数据类型的时间。

我是使用R与动物园。

非常感谢!


几秒钟是最好的方式来处理这个问题。我适合Shane的代码如下我的目的,这里是结果。

# time - time in the format of dd hh:mm:ss
#       (That's the format used in cvs export from Alcatel CCS reports)
#
time.to.seconds <- function(time) {

   t <- strsplit(as.character(time), " |:")[[1]]
   seconds <- NaN

   if (length(t) == 1 )
      seconds <- as.numeric(t[1])
   else if (length(t) == 2)
      seconds <- as.numeric(t[1]) * 60 + as.numeric(t[2])
   else if (length(t) == 3)
      seconds <- (as.numeric(t[1]) * 60 * 60 
          + as.numeric(t[2]) * 60 + as.numeric(t[3]))   
   else if (length(t) == 4)
      seconds <- (as.numeric(t[1]) * 24 * 60 * 60 +
         as.numeric(t[2]) * 60 * 60  + as.numeric(t[3]) * 60 +
         as.numeric(t[4]))

   return(seconds)
}
有帮助吗?

解决方案

正如德克指出的那样,有一个名为“difftime”的对象,但它不能被添加/减掉。

> as.difftime(5, units="mins")
Time difference of 5 mins

> d <- seq(from=as.POSIXct("2003-01-01"), to=as.POSIXct("2003-01-04"), by="days")
> d
[1] "2003-01-01 GMT" "2003-01-02 GMT" "2003-01-03 GMT" "2003-01-04 GMT"

> d + as.difftime(5, units="mins")
[1] "2003-01-01 00:00:05 GMT" "2003-01-02 00:00:05 GMT"
[3] "2003-01-03 00:00:05 GMT" "2003-01-04 00:00:05 GMT"
Warning message:
Incompatible methods ("+.POSIXt", "Ops.difftime") for "+" 

看来你现在可以做到这一点:

  > as.difftime(5, units='mins')
    Time difference of 5 mins
    > d <- seq(from=as.POSIXct("2003-01-01"), to=as.POSIXct("2003-01-04"), by="days")
    > d 
    [1] "2003-01-01 GMT" "2003-01-02 GMT" "2003-01-03 GMT" "2003-01-04 GMT"
    > d + as.difftime(5, unit='mins')
    [1] "2003-01-01 00:05:00 GMT" "2003-01-02 00:05:00 GMT"
    [3] "2003-01-03 00:05:00 GMT" "2003-01-04 00:05:00 GMT"
    > d + as.difftime(5, unit='secs')
    [1] "2003-01-01 00:00:05 GMT" "2003-01-02 00:00:05 GMT"
    [3] "2003-01-03 00:00:05 GMT" "2003-01-04 00:00:05 GMT"
   >

这是与最近发布 - [R 2.15.0

其他提示

是的,虽然没有"时间"类型,可以使用的一个偏时间:

R> now <- Sys.time()
R> now
[1] "2009-09-07 08:40:32 CDT"
R> class(now)
[1] "POSIXt"  "POSIXct"
R> later <- now + 5*60
R> later
[1] "2009-09-07 08:45:32 CDT"
R> class(later)
[1] "POSIXt"  "POSIXct"
R> tdelta <- difftime(later, now)
R> tdelta
Time difference of 5 mins
R> class(tdelta)
[1] "difftime"
R> 

当你使用 动物园 包您使用的标准 POSIXt 类型为你的时间指数。这两个动物园和更新,并还强烈推荐的 包装可以使用 POSIXt, 特别是紧凑 POSIXct 类型,用于编制索引。

的境包有更多的索引的功能,并且杰夫最近加入分析的时间间隔根据ISO8601-2004年(e)规范,并给这些参考文件 ISO8601 和一个 常见问题的广泛使用标准的日期和时间格式.使用这种境的版本,可能需要换的 境发展快照上r-伪造的

[编辑:]此外,关于这个问题上的'转变':这是容易一旦你的对象 类POSIXt/POSIXct作 as.numeric() 将POSIXct至(分数)秒由于时代。R超POSIX标准和采用双在这里,所以你得毫秒的精确度:

R> options("digits.secs"=6)   ## needed so that fractional seconds are printed
R> now <- Sys.time(); difftime(Sys.time(), now)
Time difference of 0.000149 secs

R> print(as.numeric(now), digits=15)   ## print with digits for sub-second time
[1] 1252374404.22975
R> 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top