如何使用多列向量对data.table进行排序 [英] How to sort a data.table using vector of multiple columns
问题描述
我对R很陌生,并试图构建一个比较两个数据集的函数,为此我需要对多列的数据表进行排序.我肯定会有帮助,但不确定如何搜索. 到目前为止,这是我的方法:
I am pretty new to R and trying to build a function to compare two data set, in order to do that I need to sort data table on multiple columns.I am sure there will be some help somewhere but I am not sure how to search for it. This is my approach so far:
DT = data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6), v=1:9)
#column vector
keycol <- c("x","y")
DT[order(keycol)]
x y v
1: b 1 1
2: b 3 2
不知何故,它仅显示2行并删除其他记录.但是,如果我这样做:
Somehow It displays just 2 rows and removes other records.But if I do this:
> DT[order(x,y)]
x y v
1: a 1 4
2: a 3 5
3: a 6 6
4: b 1 1
5: b 3 2
6: b 6 3
7: c 1 7
8: c 3 8
9: c 6 9
它像流体一样工作. 任何人都可以使用列名向量帮助进行排序,任何帮助将不胜感激.
It works like fluid. Can anyone help with sorting using column name vector,any help will be greatly appreciated.
推荐答案
您需要?setorderv
.
library(data.table)
DT = data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6), v=1:9)
#column vector
keycol <-c("x","y")
setorderv(DT, keycol)
DT
x y v
1: a 1 4
2: a 3 5
3: a 6 6
4: b 1 1
5: b 3 2
6: b 6 3
7: c 1 7
8: c 3 8
9: c 6 9
请注意,无需将setorderv
的输出分配回DT
.该函数通过引用更新DT
.
Note that there is no need to assign the output of setorderv
back to DT
. The function updates DT
by reference.
这篇关于如何使用多列向量对data.table进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!