data.table
rleid
library(data.table)DT = data.table(grp=rep(c("A", "B", "C", "A", "B"), c(2, 2, 3, 1, 2)), value=1:10)rleid(DT$grp)# [1] 1 1 2 2 3 3 3 4 5 5
R
df <- data.frame(DT)rep(seq_along(rle(df$grp)$values), times = rle(df$grp)$lengths)# [1] 1 1 2 2 3 3 3 4 5 5
dplyr
rleid
dplyr
library(dplyr)my_rleid = rep(seq_along(rle(df$grp)$values), times = rle(df$grp)$lengths)df %>% mutate(rleid = my_rleid)
HUWWW
慕斯709654
饮歌长啸