4D数组到矩阵

时间:2016-01-30 21:13:51

标签: arrays r matrix

我想将4D数组转换为矩阵。该数组看起来像这样

, , 1, 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2, 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 1, 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

, , 2, 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

我希望将其转换为矩阵:

     [,1] [,2] [,3] [,4]
[1,]    1    3    1    3
[2,]    2    4    2    4
[3,]    5    7    5    7
[4,]    6    8    6    8

有任何想法如何使用循环来执行此操作吗?

1 个答案:

答案 0 :(得分:1)

在这种情况下,

matrix(aperm(arr, c(1,4,2,3)), nrow = 4, ncol = 4)
#      [,1] [,2] [,3] [,4]
# [1,]    1    3    1    3
# [2,]    2    4    2    4
# [3,]    5    7    5    7
# [4,]    6    8    6    8

更一般地说,

arr <- array(c(1:9, 1:9, 5:13, 5:13), c(3,3,2,2))
matrix(aperm(arr, c(1,4,2,3)), nrow = dim(arr)[1] * dim(arr)[4])
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    4    7    1    4    7
# [2,]    2    5    8    2    5    8
# [3,]    3    6    9    3    6    9
# [4,]    5    8   11    5    8   11
# [5,]    6    9   12    6    9   12
# [6,]    7   10   13    7   10   13