How to order a matrix for all columns

Ok, I'm stuck in a dead end. I read useful ideas in How to sort data by columns (columns)? but you need one more tip. I need a function that takes a matrix with an arbitrary number of columns and sorts by all columns in a sequence. For example, for a matrix foo with columns N makes the equivalent of foo[order(foo[,1],foo[,2],...foo[,N]),] . I am happy to use the with or by construct, and if necessary, determine the colnames my matrix, but I cannot figure out how to automate the collection of arguments before order (or before). Or, I have to say, I could build the whole bloody line with paste and then call , but I'm sure there is an easier way.

+4
source share
1 answer

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

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

This works because the data frame is just a list variables with some associated attributes and can be passed to functions waiting for list .

+8
source

Source: https://habr.com/ru/post/1488557/


All Articles