将矩阵转换为R中的数组

时间:2018-07-16 18:33:10

标签: arrays r matrix reshape

我有一个矩阵:mat <- matrix(c(1:100), ncol = 10) 我想将其重塑为尺寸数组:2,10,5为:

, , 1
 [1,]    1   11   21   31   41   51   61   71   81    91
 [2,]    2   12   22   32   42   52   62   72   82    92
, , 2
 [1,]    3   13   23   33   43   53   63   73   83    93
 [2,]    4   14   24   34   44   54   64   74   84    94
, , 3
 [1,]   5   15   25   35   45   55   65   75   85    95
 [2,]     6   16   26   36   46   56   66   76   86    96
, , 4
 [1,]    7   17   27   37   47   57   67   77   87    97
 [2,]    8   18   28   38   48   58   68   78   88    98
, , 5
 [1,]    9   19   29   39   49   59   69   79   89    99
 [2,]    10   20   30   40   50   60   70   80   90   100

1 个答案:

答案 0 :(得分:1)

您可以通过按行切割mat然后将其重建为矩阵来实现。参见Plunkr url

lvl <- (nrow(mat)/2)
array(unlist(by(mat, INDICES = rep(1:lvl, each = 2), FUN = function(x) x)),
      dim = c(2, ncol(mat), lvl))

, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1   11   21   31   41   51   61   71   81    91
[2,]    2   12   22   32   42   52   62   72   82    92

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    3   13   23   33   43   53   63   73   83    93
[2,]    4   14   24   34   44   54   64   74   84    94

, , 3

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    5   15   25   35   45   55   65   75   85    95
[2,]    6   16   26   36   46   56   66   76   86    96

, , 4

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    7   17   27   37   47   57   67   77   87    97
[2,]    8   18   28   38   48   58   68   78   88    98

, , 5

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    9   19   29   39   49   59   69   79   89    99
[2,]   10   20   30   40   50   60   70   80   90   100