# example data
DT = data.table(iris)
To modify factor levels by reference, use setattr
:
setattr(DT$Species, "levels", c("set", "ver", "vir")
# or
DT[, setattr(Species, "levels", c("set", "ver", "vir"))]
The second option might print the result to the screen.
With setattr
, we avoid the copy usually incurred when doing levels(x) <- lvls
, but it will also skip some checks, so it is important to be careful to assign a valid vector of levels.