user5987132 user5987132 - 1 month ago 10
R Question

How to reverse rows in matrix?

I'm trying to reverse the order of the rows from the matrix m, so instead of getting this like in the following:

n <- rbind(m)
n

[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 6 7 8 9 10
[3,] 11 12 13 14 15
[4,] 16 17 18 19 20
[5,] 21 22 23 24 25


I want to get this instead:

[,1] [,2] [,3] [,4] [,5]
[5,] 21 22 23 24 25
[4,] 16 17 18 19 20
[3,] 11 12 13 14 15
[2,] 6 7 8 9 10
[1,] 1 2 3 4 5


Thanks for your help! Still learning the basics!

Answer

We can combine apply() and rev() to the matrix n and rearrange the entries:

n <- matrix(1:25, 5, byrow = TRUE)
apply(n,2,rev)
#     [,1] [,2] [,3] [,4] [,5]
#[1,]   21   22   23   24   25
#[2,]   16   17   18   19   20
#[3,]   11   12   13   14   15
#[4,]    6    7    8    9   10
#[5,]    1    2    3    4    5

By using apply() with the second parameter (the margin) equal to 2 we loop through all the columns of n, and for each column we apply the function rev(), which reverses the entries of a vector.


A more compact and faster way to obtain the same result is the solution pointed out by @Cath:

n[nrow(n):1,]

This simply reverses the order of the rows in the matrix.

Comments