将R 3D阵列转换为堆叠的矩阵

发布于 2025-02-04 00:56:54 字数 1051 浏览 3 评论 0原文

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2025-02-11 00:56:54

使用Aperm,我们通过将其尺寸放置并可以调整大小来转换数组:

y <- aperm(a, c(1, 3, 2))
dim(y) <- c(prod(dim(a)[-2]), dim(a)[2])

y
       [,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

With aperm we transpose an array by permuting its dimensions and optionally resizing it:

y <- aperm(a, c(1, 3, 2))
dim(y) <- c(prod(dim(a)[-2]), dim(a)[2])

y
       [,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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文