Carl Witthoft
Carl Witthoft

Reputation: 21492

How to order a matrix by all columns

Ok, I'm stuck in a dumbness loop. I've read thru the helpful ideas at How to sort a dataframe by column(s)? , but need one more hint. I'd like a function that takes a matrix with an arbitrary number of columns, and sorts by all columns in sequence. E.g., for a matrix foo with N columns, does the equivalent of foo[order(foo[,1],foo[,2],...foo[,N]),] . I am happy to use a with or by construction, and if necessary define the colnames of my matrix, but I can't figure out how to automate the collection of arguments to order (or to with) . Or, I should say, I could build the entire bloody string with paste and then call it, but I'm sure there's a more straightforward way.

Upvotes: 4

Views: 113

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57686

The most elegant (for certain values of "elegant") way would be to turn it into a data frame, and use do.call:

foo[do.call(order, as.data.frame(foo)), ]

This works because a data frame is just a list of variables with some associated attributes, and can be passed to functions expecting a list.

Upvotes: 8

Related Questions