Student
Student

Reputation: 75

Sort matrix according to all rows in R

I have a matrix M with many rows that I would like to sort such that the order of rows within a column is fixed, but that the columns are reordered.

I know that I could achieve this with code like this:

M[,order(M[1,],M[2,],M[3,],M[4,])]

but how do I generalize this code so that it works for more than 4 rows?

Upvotes: 2

Views: 106

Answers (1)

akrun
akrun

Reputation: 886998

We can convert to data.frame and use do.call with order

res <- M[,do.call(order, as.data.frame(t(M))[1:4])]
#OP's code
res2 <- M[,order(M[1,],M[2,],M[3,],M[4,])]
identical(res, res2)
#[1] TRUE

data

set.seed(1)
M <- matrix(sample(1:25), 5, 5)

Upvotes: 4

Related Questions