复制二维矩阵,创建三维数组(在R中)

时间:2022-10-17 15:50:47

I have a two dimensional matrix that I would like to replicate 10 times to create a three dimensional array where each 'slice' of the array is an identical copy of the two dimensional array.

我有一个二维矩阵我想要复制10次来创建一个三维数组其中每个数组的“切片”都是二维数组的一个相同的拷贝。

So, if my 2D array were to be:

所以,如果我的2D数组是:

a <- matrix(c(1:4),nrow=2)
> a
     [,1] [,2]
[1,]    1    3
[2,]    2    4

I would like as output an array like this:

我想输出一个这样的数组:

, , 1

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

, , 2

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

....

, , 10

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

I have seen this page (Duplicate matrix to form list), in which the OP was looking to duplicate matrices to a list, which I adapted to then convert to an array:

我已经看到了这个页面(表单列表的复制矩阵),其中OP希望将矩阵复制到一个列表中,然后我将其转换为一个数组:

b<-rep(list(a), 10) # from original post
array(unlist(b), dim = c(nrow(b[[1]]), ncol(b[[1]]), length(b))) # line I added

This works fine but it's a little roundabout - I was wondering if there were a way to do this in one line without going through the creation of a list.

这很好用,但有点迂回——我想知道是否有一种方法可以在一行中做到这一点,而不需要通过创建列表。

I tried applying the logic of a do.call in the way that is done with rbind to bind multiple rows together, but using abind instead -

我试着运用“做”的逻辑。调用rbind的方式将多个行绑定在一起,而是使用abind。

do.call(abind,as.list(c(a,a,a,a,a,a,a,a,a,a))) 

but the output was one long vector and so not what I was looking for.

但是输出是一个长矢量,不是我想要的。

Any help is greatly appreciated!

非常感谢您的帮助!

1 个解决方案

#1


3  

you can use replicate, which produces a list by default. To get an array, add simplify = "array".

您可以使用duplicate,它在默认情况下生成一个列表。要获得数组,请添加simplify = "。

replicate(10, a, simplify="array")

, , 1

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

, , 2

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

...

, , 9

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

, , 10

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

#1


3  

you can use replicate, which produces a list by default. To get an array, add simplify = "array".

您可以使用duplicate,它在默认情况下生成一个列表。要获得数组,请添加simplify = "。

replicate(10, a, simplify="array")

, , 1

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

, , 2

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

...

, , 9

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

, , 10

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