将阵列内的矩阵旋转90度

时间:2017-11-25 15:22:44

标签: arrays r matrix rotation

我为我的愚蠢问题道歉,但我刚刚开始熟悉数组。

我只需要将数组中的矩阵旋转90度。

这里有一些数据和我到目前为止所尝试的内容:

mat1 = as.matrix(data.frame(col1 = c(1,2,3,4,5,6,7,8), col2 = c(2,3,'NA',5,6,7,8,9), col3 = c(3,4,5,6,7,8,9,10), col4 = c(2,3,4,1,2,6,7,8),
                            col5 = c(2,3,'NA','NA',6,7,8,9), col6 = c(1,2,3,5,6,7,8,9), col7 = c(1,2,3,4,6,7,'NA','NA')))


mat2 = as.matrix(data.frame(col1 = c('NA',2,3,4,5,6,7,8), col2 = c(2,3,1,5,6,7,8,9), col3 = c(3,4,5,6,7,8,9,'NA'), col4 = c(2,3,4,1,2,6,7,8),
                            col5 = c(2,3,11,88,6,7,8,9), col6 = c(1,2,3,5,6,7,8,9), col7 = c(1,2,3,4,6,7,'NA','NA')))

#ignore warnings
class(mat1) = 'numeric'
class(mat2) = 'numeric'

my_array = array(c(mat1, mat2), dim = c(8,7,2))

我厌倦了没有成功:

library(pracma)

ar_rot = array(dim=c(8,7,2))

for (i in 1:2) {
    ar_rot[,,i] = rot90(my_array[,,i], k = 1)
}

我认为问题在于ar_rot的索引,因为如果我将相同的代码仅应用于一个矩阵,例如

ar_rot_1 = rot90(my_array[,,1], k = 1)

它有效!但我的阵列有数千个矩阵!

任何提示? 感谢

1 个答案:

答案 0 :(得分:0)

通过将数组转换为列表,应用函数然后将列表转换回数组,我找到了解决问题的方法:

lst = lapply(seq(dim(my_array)[3]), function(x) my_array[ , , x]) #convert to list
lst = lapply(lst, function(x) rot90(x, 1)) #rotate

#convert list back to array
ar_rot = array(as.numeric(unlist(lst)), dim=c(7, 8, 2))

> print(ar_rot)
, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    2    3    4    6    7   NA   NA
[2,]    1    2    3    5    6    7    8    9
[3,]    2    3   NA   NA    6    7    8    9
[4,]    2    3    4    1    2    6    7    8
[5,]    3    4    5    6    7    8    9   10
[6,]    2    3   NA    5    6    7    8    9
[7,]    1    2    3    4    5    6    7    8

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    2    3    4    6    7   NA   NA
[2,]    1    2    3    5    6    7    8    9
[3,]    2    3   11   88    6    7    8    9
[4,]    2    3    4    1    2    6    7    8
[5,]    3    4    5    6    7    8    9   NA
[6,]    2    3    1    5    6    7    8    9
[7,]   NA    2    3    4    5    6    7    8