与白天跳跃的时差(午夜)

时间:2014-05-09 18:17:49

标签: r time-series date-formatting

我试图计算data.frame中两次连续观察之间的时间差,称为temp。我有时间和日期:

           id version       date     time
872169 261986       0 2012-01-13 24:24:34
872170 262026       0 2012-01-13 24:26:11
872171 262037       0 2012-01-13 00:02:46
872172 262053       0 2012-01-14 00:10:28
872173 262074       0 2012-01-14 00:28:42
872174 262090       0 2012-01-15 14:29:31

时间向量的类当然是times。 现在我可以创建一个包含差异的向量:

count< - as.difftime(temp [,6],units =“mins”)

但我如何解释这些日子呢?我尝试了几件事:我将日期和时间向量结合起来:

as.difftime(paste(temp[,4], temp[,6]), unit="min")

但这只给了我NA。

另外

as.difftime(strptime( paste(temp[,4], temp[,6]), "%Y-%m-%d %H:%M:%S"), unit="mins")

没用。

difftime()也不起作用,因为日期不在两个不同的向量中。我可以想到复制日期向量并向上移动它,以便第二个日期向量的第一个值是第一个日期向量的第二个元素。但必须有更聪明的东西。

提前致谢!

1 个答案:

答案 0 :(得分:1)

使用两列作为输入:

> temp <- read.table(text="           id version       date     time
+ 872169 261986       0 2012-01-13 24:24:34
+ 872170 262026       0 2012-01-13 24:26:11
+ 872171 262037       0 2012-01-13 00:02:46
+ 872172 262053       0 2012-01-14 00:10:28
+ 872173 262074       0 2012-01-14 00:28:42
+ 872174 262090       0 2012-01-15 14:29:31", header=TRUE, stringsAsFactors=FALSE)

# didn't actually need the as.character but you probably have factor variables

> temp$tm <- as.POSIXct( paste(as.character(temp[[3]]), as.character(temp[[4]]) ) )
> temp$count <- c(NA, as.numeric(diff( temp$tm , units="min"))/60 )
> temp
           id version       date     time         tm count
872169 261986       0 2012-01-13 24:24:34 2012-01-13    NA
872170 262026       0 2012-01-13 24:26:11 2012-01-13     0
872171 262037       0 2012-01-13 00:02:46 2012-01-13     0
872172 262053       0 2012-01-14 00:10:28 2012-01-14  1440
872173 262074       0 2012-01-14 00:28:42 2012-01-14     0
872174 262090       0 2012-01-15 14:29:31 2012-01-15  1440

我发现你的日期时间不正确;同时使用&#34; 24&#34;和&#34; 00&#34;几个小时。这是没有意义的。如果我们将24更改为23,则按预期工作:

> temp$tm <- as.POSIXct( paste(as.character(temp[['date']]), as.character(temp[['time']]) ) )
>     temp$count <- c(NA, as.numeric(diff( temp$tm , units="min"))/60 )
> temp
           id version       date     time                  tm        count
872169 261986       0 2012-01-13 23:24:34 2012-01-13 23:24:34           NA
872170 262026       0 2012-01-13 23:26:11 2012-01-13 23:26:11   0.02694444
872171 262037       0 2012-01-13 00:02:46 2012-01-13 00:02:46 -23.39027778
872172 262053       0 2012-01-14 00:10:28 2012-01-14 00:10:28  24.12833333
872173 262074       0 2012-01-14 00:28:42 2012-01-14 00:28:42   0.30388889
872174 262090       0 2012-01-15 14:29:31 2012-01-15 14:29:31  38.01361111
相关问题