Cedric
Cedric

Reputation: 2474

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

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 ?

Upvotes: 3

Views: 73

Answers (2)

Matt W.
Matt W.

Reputation: 3722

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

Upvotes: 1

Glaud
Glaud

Reputation: 733

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

Upvotes: 2

Related Questions