R中行之间的日期时间差异

Mis*_*shu 9 r

我想计算R中的时间差(增量时间).时间戳存储在两列数据框中,时间为日期时间(年 - 月 - 日小时:分:秒.msec),例如前三个行:

c_id    c_time
6875    2012-08-15 00:00:40.169
6874    2012-08-15 00:01:40.055
6876    2012-08-15 00:02:40.542
Run Code Online (Sandbox Code Playgroud)

我想输出一个有差异的列,例如

c_diff
0
00:01:0.886
00:01:0.487
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我该怎么做?如果您有其他/更好的建议如何保持结果,将非常感谢提前非常感谢!秘书科

Sim*_*lon 7

试试这个(我假设你有一个data.frame被调用的数据mydf)并且你想要第一个时间戳和所有后续时间戳之间的差异:

c_time <- as.POSIXlt( mydf$c_time )
difftime( c_time[1] , c_time[2:length(c_time)] )
  #Time differences in secs
  #[1]  -59.886 -120.373
  #attr(,"tzone")
  #[1] ""
Run Code Online (Sandbox Code Playgroud)

编辑

但是如果你想要后续时间戳之间的增量差异,你需要反转你的观察(因为第一种方式你得到time1 - time2这将是负面的),所以你可以改为使用:

c_time <- rev( c_time )
difftime(c_time[1:(length(c_time)-1)] , c_time[2:length(c_time)])
  #Time differences in secs
  #[1] 60.487 59.886
  #attr(,"tzone")
  #[1] ""
Run Code Online (Sandbox Code Playgroud)