Sorting a matrix with order, using all columns, when you don't know the number of columns

怎甘沉沦 提交于 2019-12-12 14:37:24

问题


I have a dataframe that is generated dynamically from recursive left join, how can I use the order function to apply on all columns when I don't know in advance the number of columns ? I want the result sorted first on first column, then on the second ...

In the example below, I have four columns

set.seed(123)
A <- matrix(rep(1:25,4)[order(rnorm(100))],ncol=4)
B <- A[order(A[,1],A[,2],A[,3],A[,4],decreasing=TRUE),]

So I wrote this A[,1],A[,2],A[,3],A[,4] but how do I do if I don't know the number of columns ?


回答1:


Create string like A[,1],A[,2],A[,3],A[,4] in loop and next use parse and eval function to evaluate your expression.

set.seed(123)
A <- matrix(rep(1:25,4)[order(rnorm(100))],ncol=4)
col <- ""
for (i in 1:ncol(A)){
  col <- paste(col,paste0('A[,',i,']'), sep = ",")
}
## remove first comma
col <- substr(col, 2, nchar(col))
col
[1] "A[,1],A[,2],A[,3],A[,4]"
B <- eval(parse(text = paste("A[order(",col,",decreasing=TRUE),]")))



回答2:


I took Glaud's answer and added a couple tweaks:

You can do the whole thing in one line without using a for loop.

eval(parse(text = paste("A[order(",paste(paste0("A[,",1:ncol(A1),"]"), collapse = ","),",decreasing=TRUE),]")))

The following bit will get you the list of columns (which I then replaced Glaud's col for loop with):

paste(paste0("A[,",1:ncol(A1),"]"), collapse = ",")

I think it'd be cool to functionitize it which I can add to this post in a bit



来源:https://stackoverflow.com/questions/47374892/sorting-a-matrix-with-order-using-all-columns-when-you-dont-know-the-number-o

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