Dail Dail - 3 months ago 16
R Question

How to reverse a matrix in R?

I have a simple matrix like:

> a = matrix(c(c(1:10),c(10:1)), ncol=2)
> a
[,1] [,2]
[1,] 1 10
[2,] 2 9
[3,] 3 8
[4,] 4 7
[5,] 5 6
[6,] 6 5
[7,] 7 4
[8,] 8 3
[9,] 9 2
[10,] 10 1


I would like to get this result:

[,1] [,2]
[1,] 10 1
[2,] 9 2
[3,] 8 3
[4,] 7 4
[5,] 6 5
[6,] 5 6
[7,] 4 7
[8,] 3 8
[9,] 2 9
[10,] 1 10


The exact reverse of the matrix. How can I get it?
Thanks

Answer

Try rev with apply:

> a <- matrix(c(1:10,10:1), ncol=2)
> a
      [,1] [,2]
 [1,]    1   10
 [2,]    2    9
 [3,]    3    8
 [4,]    4    7
 [5,]    5    6
 [6,]    6    5
 [7,]    7    4
 [8,]    8    3
 [9,]    9    2
[10,]   10    1
> b <- apply(a, 2, rev)
> b
      [,1] [,2]
 [1,]   10    1
 [2,]    9    2
 [3,]    8    3
 [4,]    7    4
 [5,]    6    5
 [6,]    5    6
 [7,]    4    7
 [8,]    3    8
 [9,]    2    9
[10,]    1   10
Comments