1

I have some data that I am trying to group by consecutive values in R. This solution is similar to what I am looking for, however my data is structured like this:

line_num
1
2
3
1
2
1
2
3
4

What I want to do is group each time the number returns to 1 such that I get groups like this:

line_num group_num)
1 1
2 1
3 1
1 2
2 2
1 3
2 3
3 3
4 3

Any ideas on the best way to accomplish this using dplyr or base R? Thanks!

Deez
  • 25
  • 4

1 Answers1

2

We could use cumsum on a logical vector

library(dplyr)
df2 <- df1 %>%
    mutate(group_num = cumsum(line_num == 1))

or with base R

df1$group_num <- cumsum(df1$line_num == 1)

data

df1 <- structure(list(line_num = c(1L, 2L, 3L, 1L, 2L, 1L, 2L, 3L, 4L
)), class = "data.frame", row.names = c(NA, -9L))
akrun
  • 874,273
  • 37
  • 540
  • 662