I'd like to order a data.table
by a variable holding the name of a column:
I've tried every combination of + eval,
getand
c` without success:
I have colVar = "someColumnName"
I'd like to apply this to: DT[order(colVar)]
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With