Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order data.table by a character vector of column names

I'd like to order a data.table by a variable holding the name of a column:

I've tried every combination of + eval, getandc` without success:

I have colVar = "someColumnName"

I'd like to apply this to: DT[order(colVar)]

like image 353
hibernado Avatar asked Dec 10 '14 11:12

hibernado


2 Answers

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
like image 122
David Arenburg Avatar answered Oct 12 '22 08:10

David Arenburg


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
like image 44
andrewzm Avatar answered Oct 12 '22 07:10

andrewzm