How to create a consecutive group number

In the new dplyr 1.0.0 we can use cur_group_id() which gives a unique numeric identifier to a group.

library(dplyr)
df %>% group_by(site) %>% mutate(number = cur_group_id())

#  site score number
#  <int> <int>  <int>
#1     1    10      1
#2     1    11      1
#3     1    12      1
#4     4    10      2
#5     4    11      2
#6     4    11      2
#7     8     9      3
#8     8     8      3
#9     8     7      3

data

df <- structure(list(site = c(1L, 1L, 1L, 4L, 4L, 4L, 8L, 8L, 8L), 
score = c(10L, 11L, 12L, 10L, 11L, 11L, 9L, 8L, 7L)), 
class = "data.frame", row.names = c(NA, -9L))

Leave a Comment