library(data.table) rleid(sdf$s) #[1] 1 2 3 3 3 3 4 5 6 7 7 7 7
# if no package to be loaded: x = rle(as.character(sdf$s))$lengths #rle calculates lengths of equal values # x # [1] 1 1 4 1 1 1 4 rep(seq_along(x), x) #[1] 1 2 3 3 3 3 4 5 6 7 7 7 7