rleid(..., prefix=NULL)
rleidv(x, cols=seq_along(x), prefix=NULL)
NULL
(default) or a character vector of length=1 which is prefixed to the row ids, returning a character vector (instead of an integer vector).prefix = NULL
, an integer vector with same length as NROW(x)
, else a character vector with the value in prefix
prefixed to the ids obtained.
rle
). The use for such a function has come up repeatedly on StackOverflow, see the See Also
section. This function allows to generate "run-length" groups directly. rleid
is designed for interactive use and accepts a sequence of vectors as arguments. For programming, rleidv
might be more useful.
data.table
, rowid
, http://stackoverflow.com/q/21421047/559784
DT = data.table(grp=rep(c("A", "B", "C", "A", "B"), c(2,2,3,1,2)), value=1:10)
rleid(DT$grp) # get run-length ids
rleidv(DT, "grp") # same as above
rleid(DT$grp, prefix="grp") # prefix with 'grp'
# get sum of value over run-length groups
DT[, sum(value), by=.(grp, rleid(grp))]
DT[, sum(value), by=.(grp, rleid(grp, prefix="grp"))]
Run the code above in your browser using DataLab