Q:

Is there a way in R to group by 'runs'?

Say I have:
df<-data.frame(group=c(1, 1, 1, 1, 2, 2, 2, 2), 
               date=c("2000-01-01", "2000-01-02", "2000-01-04", "2000-01-05", "2000-01-09", "2000-01-10", "2000-01-11", "2000-01-13"),
               want_group=c(1, 1, 2, 2, 3,3,3,4))

I want to create a want_group variable that groups by date, group, and whether they were "daily". So for example I want to create unique id's for within group 1 for the 1st and 2nd, and then a new unique id for the 4th and 5th, and then similarly for group 2 for the 9th, 10th, and 11th. 
  group       date want_group
1     1 2000-01-01          1
2     1 2000-01-02          1
3     1 2000-01-04          2
4     1 2000-01-05          2
5     2 2000-01-09          3
6     2 2000-01-10          3
7     2 2000-01-11          3
8     2 2000-01-13          4

Thanks,

A:

We can use diff and cumsum to calculate the runs. This increments everytime the difference in date is more than 1.
df$new <- cumsum(c(TRUE, diff(as.Date(df$date)) > 1))
df

#  group       date want_group new
#1     1 2000-01-01          1   1
#2     1 2000-01-02          1   1
#3     1 2000-01-04          2   2
#4     1 2000-01-05          2   2
#5     2 2000-01-09          3   3
#6     2 2000-01-10          3   3
#7     2 2000-01-11          3   3
#8     2 2000-01-13          4   4

We add TRUE in the beginning since diff returns output of length 1 less than the original vector.

To handle this by group we can do
library(dplyr)

df %>%
  mutate(date = as.Date(date)) %>%
  group_by(group) %>%
  mutate(new = c(TRUE, diff(date) > 1)) %>%
  ungroup() %>%
  mutate(new = cumsum(new))

