问题
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
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.
回答1:
You need ?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
Note that there is no need to assign the output of setorderv
back to DT
. The function updates DT
by reference.
来源:https://stackoverflow.com/questions/50282341/how-to-sort-a-data-table-using-vector-of-multiple-columns