Tutorial by Examples

# example data DT = as.data.table(mtcars, keep.rownames = TRUE) Editing a column Use the := operator inside j to create new columns or modify existing ones: DT[, mpg_sq := mpg^2] Editing on a subset of rows Use the i argument to subset to rows "where" edits should be made: DT[1:...
# example data DT = as.data.table(mtcars, keep.rownames = TRUE) To rearrange the order of columns, use setcolorder. For example, to reverse them setcolorder(DT, rev(names(DT))) This costs almost nothing in terms of performance, since it is just permuting the list of column pointers in the da...
# example data DT = as.data.table(mtcars, keep.rownames = TRUE) To rename a column (while keeping its data the same), there is no need to copy the data to a column with a new name and delete the old one. Instead, we can use setnames(DT, "mpg_sq", "mpq_squared") to modify ...
# 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 sec...

Page 1 of 1