子集3维数组时,请不要丢弃维 [英] Don't drop dimensions when subseting 3-dimensional array
本文介绍了子集3维数组时,请不要丢弃维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让 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
然后 A [,, 1]
是无量纲的:
> A[,,1]
[1] 0 0
我想要:
[,1] [,2]
[1,] 0 0
drop
参数不能产生我想要的:
The drop
argument does not yield what I want:
> A[,,1,drop=FALSE]
, , 1
[,1] [,2]
[1,] 0 0
我觉得很烦.越野车,因为R将向量标识为列矩阵,而不是行矩阵.
I find that annoying. And buggy, because R identifies vectors to column matrices, not to row matrices.
我当然可以做 matrix(A [,, 1],1,2)
.有没有更方便的方法?
Of course I could do matrix(A[,,1], 1, 2)
. Is there a more convenient way?
推荐答案
我们可以根据提取的 MARGIN
分配 dim
We can just assign the dim
based on the MARGIN
we are extracting
`dim<-`(A[, ,1], apply(A, 3, dim)[,1])
# [,1] [,2]
#[1,] 0 0
使用另一个示例
B <- array(0, dim = c(2, 1, 2))
`dim<-`(B[, ,1], apply(B, 3, dim)[,1])
# [,1]
#[1,] 0
#[2,] 0
如果我们使用的是打包解决方案,那么 abind
中的 adrop
可能会获得预期的输出
If we are using a package solution, then adrop
from abind
could get the expected output
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
这篇关于子集3维数组时,请不要丢弃维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文