我在R中有一个像这样的矩阵:
|1|2|3|
|1|2|3|
|1|2|3|
是否有一种简单的方法可以将整个矩阵顺时针旋转90度以获得这些结果?
|1|1|1|
|2|2|2|
|3|3|3|
再次旋转90度:
|3|2|1|
|3|2|1|
|3|2|1|
答案 0 :(得分:82)
t
不会旋转条目,它会沿着对角线翻转:
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
R矩阵顺时针旋转90度:
您还需要在转置之前反转列:
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
R矩阵逆时针旋转90度:
在反向之前进行转置与逆时针旋转相同:
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
答案 1 :(得分:27)
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
答案 2 :(得分:7)
将矩阵旋转 180°的简单方法是:
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
答案 3 :(得分:2)
#first reverse, then transpose, it's the same as rotate 90 degrees
rotate_clockwise <- function(x) { t( apply(x, 2, rev))}
#first transpose, then reverse, it's the same as rotate -90 degrees:
rotate_counter_clockwise <- function(x) { apply( t(x),2, rev)}
#or if you want a library to help make things easier to read:
#install.packages("pracma")
library(pracma)
rotate_one_eighty <- function(x) { rot90(x, 2) }
rotate_two_seventy <- function(x) { rot90(x, -1) }
foo = matrix(1:9, 3)
foo
foo = rotate_clockwise(foo)
foo
foo = rotate_counter_clockwise(foo)
foo
foo = rotate_one_eighty(foo)
foo
打印:
[,1] [,2] [,3]
[1,] 1 4 7 #original matrix
[2,] 2 5 8
[3,] 3 6 9
[,1] [,2] [,3]
[1,] 3 2 1
[2,] 6 5 4 #rotated 90 degrees
[3,] 9 8 7
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8 #rotated -90 degrees
[3,] 3 6 9
[,1] [,2] [,3]
[1,] 9 6 3
[2,] 8 5 2 #rotated 180 degrees
[3,] 7 4 1
请注意,顺时针旋转矩阵,然后逆时针将数字返回到原始位置,然后旋转180就像旋转90次一样。
答案 4 :(得分:0)
或组合在一个功能中(基于Eric Leschinski):
rotate <- function(x, clockwise=T) {
if (clockwise) { t( apply(x, 2, rev))
} else {apply( t(x),2, rev)}
}