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.
Asked
Active
Viewed 106 times
4

Community
- 1
- 1

Carl Witthoft
- 20,573
- 9
- 43
- 73
1 Answers
8
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
.

Hong Ooi
- 56,353
- 13
- 134
- 187
-
Thank you! I'd been mucking with `do.call` and just plain forgot about coercing to a dataframe. – Carl Witthoft Jun 27 '13 at 18:38