如果日期相同或+ - 7天合并2行,且ID相同

时间:2017-09-24 10:20:04

标签: r dataframe iteration

所以我一直试图解决这个问题,但我无法弄清楚如何去做。

这是一个例子:

ID  Hosp. date  Discharge date
1   2006-02-02  2006-02-04
1   2006-02-04  2006-02-18
1   2006-02-22  2006-03-24
1   2008-08-09  2008-09-14
2   2004-01-03  2004-01-08
2   2004-01-13  2004-01-15
2   2004-06-08  2004-06-28

我想要的是一种按ID组合行的方法,如果discarge日期与Hosp相同。下一行中的日期(或+ -7天)。所以它看起来像这样:

ID  Hosp. date  Discharge date
1   2006-02-02  2006-03-24
1   2008-08-09  2008-09-14
2   2004-01-03  2004-01-15
2   2004-06-08  2004-06-28

1 个答案:

答案 0 :(得分:3)

使用data.table - 包:

# load the package
library(data.table)

# convert to a 'data.table'
setDT(d)
# make sure you have the correct order
setorder(d, ID, Hosp.date)

# summarise
d[, grp := cumsum(Hosp.date > (shift(Discharge.date, fill = Discharge.date[1]) + 7))
  , by = ID
  ][, .(Hosp.date = min(Hosp.date), Discharge.date = max(Discharge.date))
    , by = .(ID,grp)]

你得到:

   ID grp  Hosp.date Discharge.date
1:  1   0 2006-02-02     2006-03-24
2:  1   1 2008-08-09     2008-09-14
3:  2   0 2004-01-03     2004-01-15
4:  2   1 2004-06-08     2004-06-28

dplyr相同的逻辑:

library(dplyr)
d %>% 
  arrange(ID, Hosp.date) %>%
  group_by(ID) %>% 
  mutate(grp = cumsum(Hosp.date > (lag(Discharge.date, default = Discharge.date[1]) + 7))) %>% 
  group_by(grp, add = TRUE) %>% 
  summarise(Hosp.date = min(Hosp.date), Discharge.date = max(Discharge.date))

使用过的数据:

d <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L),
                    Hosp.date = structure(c(13181, 13183, 13201, 14100, 12420, 12430, 12577), class = "Date"),
                    Discharge.date = structure(c(13183, 13197, 13231, 14136, 12425, 12432, 12597), class = "Date")),
               .Names = c("ID", "Hosp.date", "Discharge.date"), class = "data.frame", row.names = c(NA, -7L))