Is there a dplyr equivalent to data.table::rleid?

前端 未结 4 1663
灰色年华
灰色年华 2020-11-22 13:16

data.table offers a nice convenience function, rleid for run-length encoding:

library(data.table)
DT = data.table(grp=rep(c(\"A\", \"B\", \"C\",         


        
4条回答
  •  萌比男神i
    2020-11-22 14:03

    A simplification (involving no additional package) of the approach used by the OP could be:

    DT %>%
     mutate(rleid = with(rle(grp), rep(seq_along(lengths), lengths)))
    
       grp value rleid
    1    A     1     1
    2    A     2     1
    3    B     3     2
    4    B     4     2
    5    C     5     3
    6    C     6     3
    7    C     7     3
    8    A     8     4
    9    B     9     5
    10   B    10     5
    

    Or:

    DT %>%
     mutate(rleid = rep(seq(ls <- rle(grp)$lengths), ls))
    

提交回复
热议问题