2012-09-29 157 views
18

我有一个数据,其中300万条记录的start.time和end.time作为两个变量。前10个obs如下:计算R中的时间差异

start.date start.time end.date end.time 
1 2012-07-13 15:01:32 2012-07-13 15:02:42 
2 2012-07-05 18:26:31 2012-07-05 18:27:19 
3 2012-07-14 20:23:21 2012-07-14 20:24:11 
4 2012-07-29 16:09:54 2012-07-29 16:10:48 
5 2012-07-21 14:58:32 2012-07-21 15:00:17 
6 2012-07-04 15:36:31 2012-07-04 15:37:11 
7 2012-07-22 18:28:31 2012-07-22 18:28:50 
8 2012-07-09 21:08:42 2012-07-09 21:09:02 
9 2012-07-05 09:44:52 2012-07-05 09:45:05 
10 2012-07-02 18:50:47 2012-07-02 18:51:38 

我需要计算start.time和end.time之间的差异。

我用下面的代码:

mbehave11$diff.time <- difftime(mbehave11$end.time, mbehave11$start.time, units="secs") 

但我收到此错误:

Error in as.POSIXlt.character(x, tz, ...) : 
    character string is not in a standard unambiguous format 
In addition: Warning messages: 
1: In is.na.POSIXlt(strptime(xx, f <- "%Y-%m-%d %H:%M:%OS", tz = tz)) : 
    Reached total allocation of 1535Mb: see help(memory.size) 
+0

你能提供一个可重现的例子吗?你可以阅读这个更多的信息:http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Dason

回答

32

必须把你的字符串为日期对象,你可以做日期/时间算术运算之前。试试这个:

一)阅读您的数据:

R> dat <- read.table(textConnection("start.date start.time end.date end.time 
2012-07-13 15:01:32 2012-07-13 15:02:42 
2012-07-05 18:26:31 2012-07-05 18:27:19 
2012-07-14 20:23:21 2012-07-14 20:24:11"), header=TRUE) 

b)就一个观察工作:

R> strptime(paste(dat[,1], dat[,2]), "%Y-%m-%d %H:%M:%S") 
[1] "2012-07-13 15:01:32" "2012-07-05 18:26:31" "2012-07-14 20:23:21" 

C)在现场工作,转换成数字:

​​
+0

但是结果会是什么意思?我的意思是结果-70 -48 -50 ..我如何将它们解释为分钟的差异? – user1702490

+6

请参阅'help(difftime)' - 有一个单位参数,默认为秒,您可以覆盖。但是要检查一下,在第一行看-70,并想想你在第一行设置的时间差是:七十秒。如果你想要minuts,使用'units =“min”')。这很简单。 –