Rotate a Matrix in R

前端 未结 5 1126
情歌与酒
情歌与酒 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:19

    An easy way to rotate a matrix by 180° is this:

    m <- matrix(1:8,ncol=4)
    #      [,1] [,2] [,3] [,4]
    # [1,]    1    3    5    7
    # [2,]    2    4    6    8
    
    
    rot <- function(x) "[<-"(x, , rev(x))
    
    rot(m)
    #      [,1] [,2] [,3] [,4]
    # [1,]    8    6    4    2
    # [2,]    7    5    3    1
    
    rot(rot(m))
    #      [,1] [,2] [,3] [,4]
    # [1,]    1    3    5    7
    # [2,]    2    4    6    8
    

提交回复
热议问题