Consider:
> output<-cbind(matrix(sample(15,replace = TRUE),nrow=5,ncol=3),c(sample(5,replace = TRUE)+20),c(16,16,16,16,15))
> output
[,1] [,2] [,3] [,4] [,5]
[1,] 5 8 3 25 16
[2,] 7 3 6 23 16
[3,] 7 9 7 21 16
[4,] 2 8 13 23 16
[5,] 11 1 3 22 15
Now suppose that I want to sort this by column 4, breaking ties by column 5. With order
and a little help from Stack Overflow, this is not much of a challenge:
> output[order(output[,4],output[,5]),]
[,1] [,2] [,3] [,4] [,5]
[1,] 7 9 7 21 16
[2,] 11 1 3 22 15
[3,] 7 3 6 23 16
[4,] 2 8 13 23 16
[5,] 5 8 3 25 16
My question is in a final requirement: What do I do if I want to sort my data further, by a function of any tied rows' entry in columns 1, 2 and 3? For example, how could I achieve the sort: "Sort by column 4 in increasing order. If there's a tie, sort by column 5 in increasing order. If there's also a tie in that, put the row with the lowest value in all of columns 1, 2, and 3 first (i.e. sort by min(col 1, col 2, col 3))"?
Expected output: In the above case, rows 3 and 4 of the final sort will be swapped because min(2,8,13) is less than min(7,3,6).