Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a Matrix in R by 90 degrees clockwise

I have a matrix in R like this:

|1|2|3| |1|2|3| |1|2|3| 

Is there an easy way to rotate the entire matrix by 90 degrees clockwise to get these results?

|1|1|1| |2|2|2| |3|3|3| 

and again rotating 90 degrees:

|3|2|1| |3|2|1| |3|2|1| 

?

like image 976
Johannes Avatar asked May 11 '13 10:05

Johannes


People also ask

How do you rotate a matrix clockwise?

If a standard right-handed Cartesian coordinate system is used, with the x axis to the right and the y axis up, the rotation R(θ) is counterclockwise. If a left-handed Cartesian coordinate system is used, with x directed to the right but y directed down, R(θ) is clockwise.

How do I change the orientation of a matrix in R?

Rotating or transposing R objects You simply use the t() command. The result of the t() command is always a matrix object. You can also rotate a matrix object or a table, as long as the table only has 2 dimensions.


2 Answers

t does not rotate the entries, it flips along the diagonal:

x <- matrix(1:9, 3) x ##      [,1] [,2] [,3] ## [1,]    1    4    7 ## [2,]    2    5    8 ## [3,]    3    6    9  t(x) ##      [,1] [,2] [,3] ## [1,]    1    2    3 ## [2,]    4    5    6 ## [3,]    7    8    9 

90 degree clockwise rotation of R matrix:

You need to also reverse the columns prior to the transpose:

rotate <- function(x) t(apply(x, 2, rev)) rotate(x) ##      [,1] [,2] [,3] ## [1,]    3    2    1 ## [2,]    6    5    4 ## [3,]    9    8    7  rotate(rotate(x)) ##      [,1] [,2] [,3] ## [1,]    9    6    3 ## [2,]    8    5    2 ## [3,]    7    4    1  rotate(rotate(rotate(x))) ##      [,1] [,2] [,3] ## [1,]    7    8    9 ## [2,]    4    5    6 ## [3,]    1    2    3  rotate(rotate(rotate(rotate(x)))) ##      [,1] [,2] [,3] ## [1,]    1    4    7 ## [2,]    2    5    8 ## [3,]    3    6    9 

90 degree counter clockwise rotation of R matrix:

Doing the transpose prior to the reverse is the same as rotate counter clockwise:

foo = matrix(1:9, 3) foo ## [,1] [,2] [,3] ## [1,]    1    4    7 ## [2,]    2    5    8 ## [3,]    3    6    9  foo <- apply(t(foo),2,rev) foo  ## [,1] [,2] [,3] ## [1,]    7    8    9 ## [2,]    4    5    6 ## [3,]    1    2    3 
like image 196
Matthew Lundberg Avatar answered Sep 17 '22 00:09

Matthew Lundberg


m <- matrix(rep(1:3,each=3),3)       [,1] [,2] [,3] [1,]    1    2    3 [2,]    1    2    3 [3,]    1    2    3  t(m[nrow(m):1,])       [,1] [,2] [,3] [1,]    1    1    1 [2,]    2    2    2 [3,]    3    3    3  m[nrow(m):1,ncol(m):1]       [,1] [,2] [,3] [1,]    3    2    1 [2,]    3    2    1 [3,]    3    2    1  t(m)[ncol(m):1,]       [,1] [,2] [,3] [1,]    3    3    3 [2,]    2    2    2 [3,]    1    1    1 
like image 36
Roland Avatar answered Sep 19 '22 00:09

Roland