按 id 分组并将时差(间隔)存储到列表中

Group by id and store time difference(intervals) into a list

我有日期时间排序(升序)的数据,包括 ID 和相应的时间,例如:

ID  |  Time
 1  |  2020-02-09 16:39:58
 2  |  2020-02-19 17:45:25
 1  |  2020-02-09 16:42:25
 1  |  2020-02-09 16:45:34
 2  |  2020-02-19 17:51:05
 1  |  2020-02-09 18:05:25

我想按 Id 分组,然后创建一个与每个 id 对应的列表,该列表的时间间隔以分钟为单位,例如:

 ID  |  Time_interval
  1  |  [3,3,80]
  2  |  [6]

我最接近解决这个问题的是:

df = d %>% group_by(ID) %>% mutate(Time_interval = Time - lag(Time))

但这并没有给我一个列表,它创建了一个单独的滞后列。

使用summarise将数据存储在列表中。

library(dplyr)

d %>% 
  group_by(ID) %>% 
  summarise(Time_interval = list(as.numeric(na.omit(round(difftime(Time, 
                                 lag(Time), units = 'mins')))))) -> result

result
# A tibble: 2 x 2
#     ID Time_interval
#  <int> <list>       
#1     1 <dbl [3]>    
#2     2 <dbl [1]>    

result$Time_interval

#[[1]]
#[1]  2  3 80

#[[2]]
#[1] 6

数据

d <- structure(list(ID = c(1L, 2L, 1L, 1L, 2L, 1L), Time = structure(c(1581266398, 
1582134325, 1581266545, 1581266734, 1582134665, 1581271525), class = c("POSIXct", 
"POSIXt"), tzone = "UTC")), row.names = c(NA, -6L), class = "data.frame")