【问题标题】:Calculating time intervals in R在 R 中计算时间间隔
【发布时间】:2016-08-01 01:08:36
【问题描述】:

我在这个页面上遇到了一个类似的问题:

Date-time differences between rows in R

这是我的数据的一个非常小的 sn-p:

DT  
29/07/12 20:05:01   
29/07/12 20:20:59   
30/07/12 02:42:08 
30/07/12 02:53:17 
30/07/12 02:53:18 
30/07/12 02:53:19 

我想做与这个人问的相同的事情,即计算 R 中后续行之间的时间差(增量时间)。时间戳存储在数据框中,时间为日期时间(日/月/年时:分:秒)。

此代码是好心建议的,并且大部分时间都可以使用,除了时间间隔跨越几天,然后我得到大量不正确的数字(例如 29/07/12 20:20:59 和 30/ 之间的 31472469 秒) 07/12 02:42:08。

c_time <- as.POSIXlt( mydf$c_time )
c_time <- rev( c_time )
difftime(c_time[1:(length(c_time)-1)] , c_time[2:length(c_time)])

有人有什么建议吗?

谢谢!

【问题讨论】:

    标签: r time intervals difftime


    【解决方案1】:

    最好明确格式,否则您必须仔细阅读默认选项中发生的情况:

    mydf <- read.table(text="c_time
    29/07/12 20:05:01  
    29/07/12 20:20:59  
    30/07/12 02:42:08
    30/07/12 02:53:17
    30/07/12 02:53:18
    30/07/12 02:53:19", sep=",", row.names=NULL, header=T)
    c_time <- as.POSIXlt( mydf$c_time, format="%d/%m/%y %H:%M:%S")
    c_time <- rev( c_time )
    difftime(c_time[1:(length(c_time)-1)] , c_time[2:length(c_time)])
    
    ##Time differences in secs
    ##[1]     1     1   669 22869   958
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      相关资源
      最近更新 更多