在R中旋转矩阵 [英] Rotate a Matrix in R
本文介绍了在R中旋转矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在R中有一个矩阵,像这样:
I have a matrix in R like this:
|1|2|3|
|1|2|3|
|1|2|3|
是否有一种简单的方法将整个矩阵顺时针旋转90度以获得这些结果?
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|
然后再次旋转90度:
|3|2|1|
|3|2|1|
|3|2|1|
?
推荐答案
t
不会旋转条目,而是沿对角线翻转:
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
R矩阵顺时针旋转90度:
您还需要在转置之前反转列:
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
R矩阵逆时针旋转90度:
在反转之前进行转置与逆时针旋转相同:
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
这篇关于在R中旋转矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文