7

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?

3
  • 12
    N<-M[,c(3:1),drop = FALSE]. Read ?Extract. This is also a FAQ. Commented Nov 6, 2013 at 19:18
  • @joran Post that as an answer. Commented Nov 7, 2013 at 19:56
  • 1
    Also, you don't need c(3:1). Only 3:1 will suffice. Commented Sep 24, 2019 at 14:53

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For loops are slow in R and this is a faster, better answer. Thanks for posting a concise, optimised answer that is usable on larger datsets.
1
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

2 Comments

B <- diag(5)[,5:1] does the same thing as your way but @joran's comment is a better way to do the whole process.
oh man. it is ....lol. I really should see the comments before I upload my answer haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.