Order data.table by a character vector of column names

浪尽此生 提交于 2020-07-08 05:27:07

问题


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)]


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/27399929/order-data-table-by-a-character-vector-of-column-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!