4

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!

Tal Avissar
  • 10,088
  • 6
  • 45
  • 70
user5987132
  • 55
  • 1
  • 1
  • 7

2 Answers2

20

The easiest way I can think of to reverse the row order of a matrix m is:

m[nrow(m):1, ]

some benchmark to compare the 2 options

m <- matrix(rnorm(50000*100), ncol=100)
library(microbenchmark)
microbenchmark(n <- m[nrow(m):1, ], n <- apply(m, 2, rev), unit="relative")

#               expr      min       lq     mean   median       uq      max neval cld
# n <- m[nrow(m):1, ] 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000   100  a 
# n <- apply(m, 2, rev) 2.947735 3.090831 2.878977 3.143367 2.954659 1.816428   100   b
Cath
  • 23,906
  • 5
  • 52
  • 86
8

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.

RHertel
  • 23,412
  • 5
  • 38
  • 64
  • 3
    not sure it will be more efficient than just `n[nrow(n):1, ]`... – Cath Apr 28 '16 at 12:22
  • Thank-you! Can you explain what apply() is doing a little? Sorry, still learning the basics. – user5987132 Apr 28 '16 at 12:22
  • 1
    @Cath I think you are right. Your solution with `n[nrow(n):1,]` should be more efficient. If you post it as an answer I'll upvote ;-) – RHertel Apr 28 '16 at 12:24