A quick question on sequential sort/order
I am trying to sort a data matrix with several columns. Here, I want to sort sequentially as in Excel. Once I sort the matrix by the first column, I would like to keep the first column, and then sort by the second column, then keep the first and second columns and then sort the rest of the matrix by the third column, and so on.
For example, if my matrix is dd
and I want to sort from 20 to 34 sequen开发者_开发问答tially:
L <- 34
for(init in 20:L){
dd <- dd[with(dd, order(dd[,init],decreasing=T)), ]
}
This does not work; can anyone advise me with a correct script for this case?
Perhaps
ord <- do.call(order,c(dd[,20:34],decreasing=TRUE))
dd <- dd[ord,]
edit: @DWin points out that as.list
is not necessary (and that the help page for ?order
has a very similar example)
edit 2: if you want the sort to be decreasing, and you need to use do.call
to specify many columns, you need to include decreasing=TRUE
in the argument list as above by using c()
to lump it in with the data frame. The following simplified example appears to work:
X <- rev(expand.grid(x=1:2,y=1:3,z=1:4))
> head(X)
z y x
1 1 1 1
2 1 1 2
3 1 2 1
4 1 2 2
5 1 3 1
6 1 3 2
ord <- do.call(order,c(X,decreasing=TRUE))
head(X[ord,])
head(X[ord,])
z y x
24 4 3 2
23 4 3 1
22 4 2 2
21 4 2 1
20 4 1 2
19 4 1 1
精彩评论