复制2维矩阵以创建3维数组(以R表示) [英] Replicating 2 dimensional matrix to create a 3 dimensional array (in R)
问题描述
我有一个二维矩阵,我想复制10次以创建一个三维数组,其中数组的每个切片"都是二维数组的相同副本.
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.
所以,如果我的2D数组是:
So, if my 2D array were to be:
a <- matrix(c(1:4),nrow=2)
> a
[,1] [,2]
[1,] 1 2
[2,] 3 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
我看过此页面(复制矩阵到表单列表),其中OP希望将矩阵复制到列表中,然后我将其转换为数组:
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:
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.
我尝试以rbind的方式应用do.call的逻辑,以将多行绑定在一起,但改用abind-
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 -
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.
任何帮助将不胜感激!
推荐答案
,您可以使用replicate
,默认情况下会生成一个列表.要获取数组,请添加simple ="array".
you can use replicate
, which produces a list by default. To get an array, add simplify = "array".
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
这篇关于复制2维矩阵以创建3维数组(以R表示)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!