Rotate a Matrix in R

前端 未结 5 1149
情歌与酒
情歌与酒 2020-11-27 12:08

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 the

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 12:29

    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
    

提交回复
热议问题