Order data.table by a character vector of column names
You can use double brackets for data tables:
library(data.table)
dtbl <- data.table(x = 1:5, y = 5:1)
colVar = "y"
dtbl_sorted <- dtbl[order(dtbl[[colVar]])]
dtbl_sorted
data.table
has special functions for that matter which will modify your data set by reference instead of copying it to a new object.
You can either use setkey
or (in versions >= 1.9.4) setorder
which is capable of ordering in decreasing order too.
Note the difference between setkey
vs. setkeyv
and setorder
vs. setorderv
. v
notes that you can pass either a quoted variable name or a variable containing one.
Using @andrewzm data set
dtbl
# x y
# 1: 1 5
# 2: 2 4
# 3: 3 3
# 4: 4 2
# 5: 5 1
setorderv(dtbl, colVar)[] # or `sekeyv(dtbl, colVar)[]` or `setorderv(dtbl, "y")[]`
# x y
# 1: 5 1
# 2: 4 2
# 3: 3 3
# 4: 2 4
# 5: 1 5