这个问题类似于几天前已经发布的问题,Collapse rows from 0 to 0
这里与上一个问题不同的新变化是,我们如何仅针对时间差异小于或等于 60 的行按 Id 折叠行。
例如,使用相同的数据集
Incident.ID.. date product
INCFI0000029582 2014-09-25 08:39:45 foo
INCFI0000029582 2014-09-25 08:39:45 foo
INCFI0000029582 2014-09-25 08:39:48 bar
INCFI0000029582 2014-09-25 08:40:44 foo
INCFI0000029582 2014-10-10 23:04:00 foo
INCFI0000029587 2014-09-25 08:33:32 bar
INCFI0000029587 2014-09-25 08:34:41 bar
INCFI0000029587 2014-09-25 08:35:24 bar
INCFI0000029587 2014-10-10 23:04:00 foo
df <- structure(list(Incident.ID.. = c("INCFI0000029582", "INCFI0000029582","INCFI0000029582",
"INCFI0000029582", "INCFI0000029582", "INCFI0000029587", "INCFI0000029587",
"INCFI0000029587", "INCFI0000029587"), date = c("2014-09-25 08:39:45","2014-09-25 08:39:45",
"2014-09-25 08:39:48", "2014-09-25 08:40:44", "2014-10-10 23:04:00",
"2014-09-25 08:33:32", "2014-09-25 08:34:41", "2014-09-25 08:35:24",
"2014-10-10 23:04:00"), product =
c("foo","foo","bar","foo","foo","bar","bar","bar","foo")),
class = "data.frame", row.names = c(NA,
-L))
这通过ID计算时间差
library(dplyr)
library(lubridate)
df1 <- df %>%
group_by(Incident.ID..) %>%
arrange(ymd_hms(date)) %>%
mutate(diff = c(0, diff(ymd_hms(date))))
这会导致这个新列差异,如下所示
Incident.ID.. date product diff
INCFI0000029582 2014-09-25 08:39:45 foo 0
INCFI0000029582 2014-09-25 08:39:45 foo 0
INCFI0000029582 2014-09-25 08:39:48 bar 3
INCFI0000029582 2014-09-25 08:40:44 foo 56
INCFI0000029582 2014-10-10 23:04:00 foo 1347796
INCFI0000029587 2014-09-25 08:33:32 bar 0
INCFI0000029587 2014-09-25 08:34:41 bar 69
INCFI0000029587 2014-09-25 08:35:24 bar 43
INCFI0000029587 2014-10-10 23:04:00 foo 1348116
Incident.ID..
现在只在时间差小于或等于 60的地方折叠行,即diff <= 60
应该产生像这样的最终数据集
Incident.ID.. DateMin DateMax product diff_collapse
INCFI0000029582 2014-09-25 08:39:45 2014-09-25 08:40:44 foo,bar,foo 0,0,3,56
INCFI0000029582 2014-09-25 08:40:44 2014-10-10 23:04:00 foo 1347796
INCFI0000029587 2014-09-25 08:33:32 2014-09-25 08:34:41 bar 0
INCFI0000029587 2014-09-25 08:34:41 2014-09-25 08:35:24 bar,bar 69,43
INCFI0000029587 2014-09-25 08:35:24 2014-10-10 23:04:00 foo 1348116
寻找有关如何创建此类折叠数据集的帮助。提前致谢。