在 R 中计算时间间隔
Calculating time intervals in R
我在这个页面上遇到了一个类似的问题:
Date-time differences between rows in R
这是我的一小段数据:
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 中后续行之间的时间差(增量时间)。时间戳存储在数据框中,时间为日期时间 (day/month/year hour:min:sec)。
此代码是友善的建议,大部分时间都有效,除了时间间隔跨越几天,然后我得到大量不正确的数字(例如 29/07/12 20:20:59 和之间的 31472469 秒2012 年 7 月 30 日 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)])
有人有什么建议吗?
谢谢!
最好明确格式,否则您必须仔细阅读默认选项中发生的情况:
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
我在这个页面上遇到了一个类似的问题:
Date-time differences between rows in R
这是我的一小段数据:
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 中后续行之间的时间差(增量时间)。时间戳存储在数据框中,时间为日期时间 (day/month/year hour:min:sec)。
此代码是友善的建议,大部分时间都有效,除了时间间隔跨越几天,然后我得到大量不正确的数字(例如 29/07/12 20:20:59 和之间的 31472469 秒2012 年 7 月 30 日 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)])
有人有什么建议吗?
谢谢!
最好明确格式,否则您必须仔细阅读默认选项中发生的情况:
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