从三维阵列到矩阵

时间:2014-02-24 19:24:01

标签: arrays r matrix

在R中,我想将一个数组(维度:i,j,k)变换成矩阵,使得新矩阵的观察(即行)是来自每次拉出k“层”的阵列的每个元素。实质上,新矩阵的行将再次由前一阵列的每个元素组成,矩阵的列等于阵列的k维。因此,新矩阵应由具有k列的i * j行组成。

如果我能澄清或提供输入/输出的示例,请告诉我。

谢谢!

编辑: 此代码有效(但未优化) -

    m = array(1:27,dim = c(3,3,3))
    m
    dim = dim(m)
    mparam = dim[3]

    listm = list()
    for (i in 1:mparam){
      listm[[i]] = as.vector(m[,,i])
    }

    untran = do.call(rbind,listm)
    transposed = t(untran)
    transposed

1 个答案:

答案 0 :(得分:2)

喜欢这个吗?

m <- array(1:27,dim = c(3,3,3))
> m
, , 1

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

, , 2

     [,1] [,2] [,3]
[1,]   10   13   16
[2,]   11   14   17
[3,]   12   15   18

, , 3

     [,1] [,2] [,3]
[1,]   19   22   25
[2,]   20   23   26
[3,]   21   24   27

> matrix(m,9,3)
      [,1] [,2] [,3]
 [1,]    1   10   19
 [2,]    2   11   20
 [3,]    3   12   21
 [4,]    4   13   22
 [5,]    5   14   23
 [6,]    6   15   24
 [7,]    7   16   25
 [8,]    8   17   26
 [9,]    9   18   27