在下三维数组时不要丢弃尺寸

Sté*_*ent 5 arrays r

让我们A成为一个1 x 2 x 2阵列:

> A <- array(0, dim=c(1,2,2))
> A
, , 1

     [,1] [,2]
[1,]    0    0

, , 2

     [,1] [,2]
[1,]    0    0
Run Code Online (Sandbox Code Playgroud)

然后A[,,1]是无量纲的:

> A[,,1]
[1] 0 0
Run Code Online (Sandbox Code Playgroud)

我想拥有:

     [,1] [,2]
[1,]    0    0
Run Code Online (Sandbox Code Playgroud)

这个drop论点没有产生我想要的东西:

> A[,,1,drop=FALSE]
, , 1

     [,1] [,2]
[1,]    0    0
Run Code Online (Sandbox Code Playgroud)

我发现这很烦人.而且有问题,因为R识别向量矩阵的向量,而不是行矩阵.

我当然能做到matrix(A[,,1], 1, 2).有更方便的方式吗?

akr*_*run 2

dim我们可以根据MARGIN我们正在提取的分配

`dim<-`(A[, ,1], apply(A, 3, dim)[,1])
 #     [,1] [,2]
 #[1,]    0    0
Run Code Online (Sandbox Code Playgroud)

使用另一个例子

B <- array(0, dim = c(2, 1, 2))
`dim<-`(B[, ,1], apply(B, 3, dim)[,1])
 #    [,1]
#[1,]    0
#[2,]    0
Run Code Online (Sandbox Code Playgroud)

如果我们使用包解决方案,那么adropfromabind可以获得预期的输出

library(abind)
adrop(A[,,1,drop=FALSE], drop = 3)
#      [,1] [,2]
# [1,]    0    0

adrop(B[,,1,drop=FALSE], drop = 3)
#     [,1]
#[1,]    0
#[2,]    0
Run Code Online (Sandbox Code Playgroud)