Group Data in R for consecutive rows
11:17 11 Sep 2015

If there's not a quick 1-3 liner for this in R, I'll definitely just use linux sort and a short python program using groupby, so don't bend over backwards trying to get something crazy working. Here's the input data frame:

df_in <- data.frame(
  ID = c(1,1,1,1,1,2,2,2,2,2),
  weight = c(150,150,151,150,150,170,170,170,171,171),
  start_day = c(1,4,7,10,11,5,10,15,20,25),
  end_day = c(4,7,10,11,30,10,15,20,25,30)
)
   ID weight start_day end_day
1   1    150         1       4
2   1    150         4       7
3   1    151         7      10
4   1    150        10      11
5   1    150        11      30
6   2    170         5      10
7   2    170        10      15
8   2    170        15      20
9   2    171        20      25
10  2    171        25      30

I would like to do some basic aggregation by ID and weight, but only when the group is in consecutive rows of df_in. Specifically, the desired output is

df_desired_out <- data.frame(
  ID = c(1,1,1,2,2),
  weight = c(150,151,150,170,171),
  min_day = c(1,7,10,5,20),
  max_day = c(7,10,30,20,30)
)
  ID weight min_day max_day
1  1    150       1       7
2  1    151       7      10
3  1    150      10      30
4  2    170       5      20
5  2    171      20      30

This question seems to be extremely close to what I want, but I'm having lots of trouble adapting it for some reason.

r