user2961927
user2961927

Reputation: 1718

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?

Upvotes: 7

Views: 15075

Answers (2)

joran
joran

Reputation: 173567

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.

Upvotes: 11

Tay Shin
Tay Shin

Reputation: 528

A=t(matrix(1:25,5,5))
B=matrix(0,5,5)
for(i in 1:5){
  B[i,(nrow(A)+1-i)]=1
}

A
# [,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

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

Upvotes: 1

Related Questions