Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a matrix in R? [duplicate]

Tags:

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

like image 966
Dail Avatar asked Feb 03 '12 21:02

Dail


People also ask

How do you reverse the order of a matrix in R?

The rev() method reverses the order of the matrix on the basis of columns.

How do you revert a matrix?

To find the inverse of a 2x2 matrix: swap the positions of a and d, put negatives in front of b and c, and divide everything by the determinant (ad-bc).

How do you reverse a column in a matrix?

To reverse column order in a matrix, we make use of the numpy. fliplr() method. The method flips the entries in each row in the left/right direction. Column data is preserved but appears in a different order than before.

How do you reverse a row in Python?

Reversing the rows of a data frame in pandas can be done in python by invoking the loc() function. The panda's dataframe. loc() attribute accesses a set of rows and columns in the given data frame by either a label or a boolean array.


2 Answers

a[nrow(a):1,] #       [,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 
like image 192
Per Avatar answered Oct 20 '22 00:10

Per


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 
like image 33
Dirk Eddelbuettel Avatar answered Oct 20 '22 01:10

Dirk Eddelbuettel