1

Consider this data frame:

DT <- data.frame(id = rep(1:3, each = 5),
                 seq = c(1,3,3,4,5,1,2,3,4,5,1,1,1,1,1)

What I want to do is create a column called nth_instance which should look like this:

DT <- data.frame(id = rep(1:3, each = 5),
                 seq = c(1,3,3,4,5,1,2,3,4,5,1,1,1,1,1),
                 nth_instance = c(1,2,2,3,4,1,2,3,4,5,1,1,1,1,1))

Create a column that counts the distinct occurrences of seq column but also in a running length fashion. It would be nice if it is a dplyr solution.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
P.R
  • 300
  • 1
  • 7

1 Answers1

2

You need data.table.

DT %>% 
  group_by(id) %>% 
  mutate(nth_instance = rleid(seq))
Theo
  • 575
  • 3
  • 8