Search code examples
r

Flip the matrix


Hi everyone who loves while hates R:

Let's say you want to turn matrix M

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

to N

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

All you need to do is

N<-M[,c(3:1)]

And N's structure is still a matrix

However, when you want to turn matrix M

       [,1] [,2] [,3]
[1,]    1    2     3  

to N

       [,1] [,2] [,3]
[1,]    3    2     1  

if you do N<-M[,c(3:1)] R will give you

N
[1] 3 2 1

N now is a vector! Not a matrix!

My solution is N<-M%*%diag(3)[,c(3:1)] which needs big space to store the identity matrix however.

Any better idea?


Solution

  • You're looking for this:

    N <- M[,c(3:1),drop = FALSE] 
    

    Read ?Extract for more information. This is also a FAQ. This behavior is one of the most common debates folks have about the way things "should" be in R. My general impression is that many people agree that drop = FALSE might be a more sensible default, but that behavior is so old that changing it would be enormously disruptive to vast swaths of existing code.