For an arbitrary matrix or dataframe x
with any number of columns, I want to do this:
x=x[order(x[,1], x[,2], ..., x[,ncol(x)]),]
That is, I want to sort by the first column, then by the second column, ..., then by the last column. The extended discussion on sorting here doesn't seem to contain the solution. Here is my solution, which violates fortune(106)
:
sortarray = function(x){
k = ncol(x)
com = paste("x = x[order(x[,", paste(1:k, collapse = "],x[,"), "]),]", sep = "")
eval(parse(text = com))
return(x)}
x = sortarray(x)
This seems to work fine, but isn't there a cleaner way?
Edit for deduplication clarification: This question is different from its suggested duplicate in an important way (at least for me). The previous question deals with the situation in which you explicitly state the columns that you want to sort by. In my case, I want the columns to be selected automatically (specifically, all of them), rather than me having to type out each column name within the ordering command. The answer below solved my problem, unlike any of the answers to the previous question.