Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order a matrix by all columns

Tags:

sorting

r

matrix

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.

like image 971
Carl Witthoft Avatar asked Feb 17 '23 02:02

Carl Witthoft


1 Answers

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.

like image 62
Hong Ooi Avatar answered Feb 27 '23 11:02

Hong Ooi