How to sort a matrix by all columns

r, sorting

Solution

This would work:

arr[do.call(order, lapply(1:NCOL(arr), function(i) arr[, i])), ]

What it is doing is:

arr[order(arr[, 1], arr[, 2], arr[ , 3]), ]

except it allows an arbitrary number of columns in the matrix.

Problem

Suppose I have ``` arr = 2 1 3 1 2 3 1 1 2 ``` How can I sort this into the below? ``` arr = 1 1 2 1 2 3 2 1 3 ``` That is, first by column one, then by column two etc.

Original source