将R 3D阵列转换为堆叠的矩阵
我有一个3D r数组,例如:
a <- array(1:27, dim = c(3,3,3))
我如何(有效地)将其转换为一个矩阵,其中3维度彼此绑定 /堆叠在该矩阵中,即:
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[4,] 10 13 16
[5,] 11 14 17
[6,] 12 15 18
[7,] 19 22 25
[8,] 20 23 26
[9,] 21 24 27
我可以用以下方式笨拙地实现这一点:
rbind(a[,,1], a[,,2], a[,,3])
但是,如果我不可推广,如果我是不可能的。在第三维中有许多条目(除循环外)。 必须有一种更优雅的方法来实现这一目标,但我找不到它。
apply(a, 3, rbind)
apply(a, 3, c)
创建一个矩阵,但第三维只是列成为列。我想保留前两个维度的2D矩阵,然后将它们绑在一起。我知道这会弄乱索引,但是我们可以将其无视我的用例。
我对基本R解决方案感到特别满意,但是如果可以使用(轻巧)软件包实现这一点,也很感兴趣。
编辑: 此答案-in-r“>看似无关的问题提供了有用的提示。这种方法似乎取得了预期的结果:
matrix(aperm(a, c(1, 3, 2)), nrow = dim(a)[1] * dim(a)[3])
还有其他想法吗?
I have a 3D R array, e.g.:
a <- array(1:27, dim = c(3,3,3))
How can I (efficiently) convert this into a matrix in which the 3rd dimension is bound / stacked below each other, i.e.:
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[4,] 10 13 16
[5,] 11 14 17
[6,] 12 15 18
[7,] 19 22 25
[8,] 20 23 26
[9,] 21 24 27
I can clumsily achieve this with:
rbind(a[,,1], a[,,2], a[,,3])
but this is not generalizable well if I have many entries in the 3rd dimension (except with looping).
There must be a more elegant way to achieve this, but I could not find it. Ideas like
apply(a, 3, rbind)
apply(a, 3, c)
create a matrix, but the 3rd dimension simply become the columns. I want to keep the 2D matrices of the first 2 dimensions and just bind them together. I am aware this will mess up the indices, but we can disregard this for my use case.
I would be especially happy about a base R solution, but am also interested if this can be achieved with a (lightweight) package.
Edit:
This answer to a seemingly unrelated question provided a useful hint. This approach seems to achieve the desired result:
matrix(aperm(a, c(1, 3, 2)), nrow = dim(a)[1] * dim(a)[3])
Are there other ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
Aperm
,我们通过将其尺寸放置并可以调整大小来转换数组:With
aperm
we transpose an array by permuting its dimensions and optionally resizing it: