计算按ID分组的时间差

时间:2017-10-28 09:15:00

标签: r

使用此代码:

idCol <- c('1','1','1','2','2','3','3')
rowNumIdCol <- c('1','2','3','4','5','6','7')
stepCol <- c('step1')
step1Col <- c('30-12-2010:11.02', '31-12-2010:10.06', '05-01-2011:15.12','01-03-2017:09.00', '01-05-2017:09.00', '01-06-2017:09.00', '01-07-2017:09.00')
mydata <- data.frame(idCol , rowNumIdCol , step1Col)
colnames(mydata) <- c('id' , 'rowNumId' , 'step1')

创建数据框:

enter image description here

我试图计算按ID分组的每个时间戳之间的差异。

以下是我尝试的代码:

mydata$"Days spent" <- unlist(by(mydata, mydata$id, function(x) as.numeric(difftime(ymd_hms(x$step1),ymd_hms(x$step1)[1], units= "days"))))

但是这会返回一个不正确的数据框&#39;所用的天数&#39;专栏:

enter image description here

364.9994&amp; -9464.9554是不正确的值。

我没有正确计算时差?

1 个答案:

答案 0 :(得分:3)

根据“step1”的formt,我们需要使用dmy_hm将其转换为“datetime”类

library(dplyr)
library(lubridate)
mydata %>% 
    group_by(id) %>% 
    mutate(DaysSpent = as.numeric(difftime(dmy_hm(step1), 
                         dmy_hm(step1)[1], units = 'days')))