rowid
is intended for interactive use, particularly along with the function dcast
to generate unique ids directly in the formula.
rowidv(dt, cols=c("x", "y"))
is equivalent to column N
in the code dt[, N := seq_len(.N), by=c("x", "y")]
.
See examples for more.
rowid(..., prefix=NULL)
rowidv(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.
dcast.data.table
, rleid
DT = data.table(x=c(20,10,10,30,30,20), y=c("a", "a", "a", "b", "b", "b"), z=1:6)
rowid(DT$x) # 1,1,2,1,2,2
rowidv(DT, cols="x") # same as above
rowid(DT$x, prefix="group") # prefixed with 'group'
rowid(DT$x, DT$y) # 1,1,2,1,2,1
rowidv(DT, cols=c("x","y")) # same as above
DT[, .(N=seq_len(.N)), by=.(x,y)]$N # same as above
# convenient usage with dcast
dcast(DT, x ~ rowid(x, prefix="group"), value.var="z")
# x group1 group2
# 1: 10 2 3
# 2: 20 1 6
# 3: 30 4 5
Run the code above in your browser using DataLab