-2

I have a numeric matrix like this:

5  2  4  6  1
2  3  3  2  5
1  1  4  5  2
3  6  2  1  0

I want to sort it by the rows of the last column to get a matrix like:

3  6  2  1  0
5  2  4  6  1
1  1  4  5  2
2  3  3  2  5

I tried to run this code:

t <- function(m){
b <- sapply(1:length(m[,1]),function(x){sort(m[x,5],decreasing=F)})
m[b,]
}

But it doesn't work. Do you suggest anything?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Fate
  • 43
  • 6

1 Answers1

1

We order by the last column to get the expected output

m[order(m[,ncol(m)]),]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    3    6    2    1    0
#[2,]    5    2    4    6    1
#[3,]    1    1    4    5    2
#[4,]    2    3    3    2    5

data

m <- structure(c(5L, 2L, 1L, 3L, 2L, 3L, 1L, 6L, 4L, 3L, 4L, 2L, 6L, 
2L, 5L, 1L, 1L, 5L, 2L, 0L), .Dim = 4:5)
akrun
  • 874,273
  • 37
  • 540
  • 662