Мы делаем lag
логического выражения и получаем накопленную сумму
library(dplyr)
df1 %>%
mutate(Group = cumsum(lag(Events == "Accident", default = TRUE)))
# Events Group
#1 A 1
#2 A 1
#3 A 1
#4 B 1
#5 C 1
#6 A 1
#7 C 1
#8 B 1
#9 Accident 1
#10 C 2
#11 C 2
#12 C 2
#13 B 2
#14 A 2
#15 Accident 2
#16 C 3
#17 A 3
#18 A 3
#19 B 3
#20 B 3
#21 Accident 3
data
df1 <- structure(list(Events = c("A", "A", "A", "B", "C", "A", "C",
"B", "Accident", "C", "C", "C", "B", "A", "Accident", "C", "A",
"A", "B", "B", "Accident")), class = "data.frame", row.names = c(NA,
-21L))