3

So i've been trying to get my head around this but i can't figure out how to do it.

This is an example:

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

What i want is a way to combine rows by ID, IF the discarge date is the same as the Hosp. date (or +-7 days) in the next row. So it would look like this:

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
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • Related: [Collapse rows with overlapping ranges](https://stackoverflow.com/questions/41747742/collapse-rows-with-overlapping-ranges) – Henrik Sep 24 '17 at 13:56

1 Answers1

3

Using the data.table-package:

# 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)]

you get:

   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

The same logic with 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))

Used data:

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))
Jaap
  • 81,064
  • 34
  • 182
  • 193