Nice, a simple modification can make this way more powerful for counting and separating groups. Let's say case 1 has no flags, 2 has one and 3 has 3:
df <- tribble(~ID, ~TIME, ~DV, ~FLAG,
1, 1, 0.1, 194,
1, 2, 0.2, 194,
1, 3, 0.3, 194,
2, 1, 0.1, 194,
2, 2, 0.2, 5000,
2, 2, 0.3, 194,
2, 2, 0.3, 194,
3, 1, 0.1, 194,
3, 2, 0.2, 5000,
3, 1, 0.2, 194,
3, 3, 0.3, 5000,
3, 4, 0.4, 194)
Then we can use the Flag as a counter and do a cumsum, by ID group. This also fixes the 0 value issue without a fill:
df %>%
group_by(ID) %>%
mutate(GROUP = cumsum(case_when(FLAG == 5000 ~ 1,
TRUE ~ 0)))
This will allow to separate ID's into different groups, depending on the logic expression. It is super useful in time series to separate windows of events by a "mother" group 