我喜欢rle这个:
foo <- rle(df$AA)
foo$values <- 1:length(foo$values)
df$BB <- inverse.rle(foo)
Run Code Online (Sandbox Code Playgroud)
我喜欢这样使用cumsum:
df$BB <- cumsum(c(1, head(df$AA, -1) != tail(df$AA, -1)))
Run Code Online (Sandbox Code Playgroud)
基准x <- sample(1:10,1e4,TRUE):
Unit: microseconds
expr min lq median uq max neval
Jus(x) 1259 1330 1936 1987 5289 100
Rol(x) 391 402 463 616 3903 100
Run Code Online (Sandbox Code Playgroud)