具有动态尺寸的数组子集部分 [英] Subset parts of array with dynamic dimension
问题描述
我想对维数为k的动态数组进行子集化.
I would like to subset an array with a dynamic number of dimensions k.
以示例为例:
A <- array(1:3^4, dim=c(3,3,3,3))
由于尺寸可以变化(此处未显示),因此我不能简单地定义a,b,c,d并通过进行查询
Because the dimensions can vary (not shown here), I cannot simply define a, b, c, d and make the query via
a <- 1:2; b <- 2; c <- 2:3; d = 1
A[a, b, c, d]
此处已显示,如果仅想对进行子集化单个元素,就可以这样处理:
Here has been shown that if one would like to subset only a single element, one can go about it like this:
e <- 1; f <- 2; g <- 3; h <- 1
A[matrix(c(e, f, g, h), nrow = 1)]
这可以使维数保持灵活,但是我只能对单个元素进行子集化,因为我无法在矩阵中表示序列a,b,c,d.
This allows me to keep the number of dimensions flexible, but I can only subset single elements, because I cannot represent the sequences a, b, c, d in a matrix.
理想的情况是我可以得到
The desired situation is that I can get the output of
A[a, b, c, d]
不对尺寸进行硬编码,即通过以下方式访问数组
without hardcoding the dimensions, i.e. access the array via
A[object]
问题基本上是可能的,如果是,对象"的外观如何.
and the question is basically is this possible and if yes how does 'object' look like.
任何帮助将不胜感激!
推荐答案
如果将 object
定义为列表,则可以使用 do.call
将该列表用作子功能 [
"的参数.如果将数组作为列表中的第一项包括在内,则可以直接调用 [
":
If you define object
as a list, you can use do.call
to use that list as parameters for the subsetting function [
. If you include the array as the first item in the list, you can call [
directly:
object <- list(A, a, b, c, d)
do.call(`[`, object)
## [,1] [,2]
## [1,] 13 22
## [2,] 14 23
如果您不希望包含数组(如果您有很多这样的对象并且数组很大,则将需要大量的内存),则可以编写一个匿名函数,仅使用子集参数,不是什么是子集:
If you don't want to include the array (if you have lots of these objects and the array is large, it will require a lot of memory), you can write an anonymous function to just use just the subsetting parameters, not what's being subset:
object <- list(a, b, c, d)
do.call(function(...){A[...]}, object)
## [,1] [,2]
## [1,] 13 22
## [2,] 14 23
这实际上是 abind :: asub
采用的确切方法:
That is actually the exact approach abind::asub
takes:
object <- list(a, b, c, d)
abind::asub(A, object)
## [,1] [,2]
## [1,] 13 22
## [2,] 14 23
请注意,此处的参数匹配是关系型的,因此,如果其中一个为空,则需要包含 NULL
:
Note that parameter matching here is relational, so if one is empty, it will need to contain NULL
:
object <- list(NULL, b, c, d)
abind::asub(A, object)
## [,1] [,2]
## [1,] 13 22
## [2,] 14 23
## [3,] 15 24
这篇关于具有动态尺寸的数组子集部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!