6

我有不同大小的列联表。我想使用数据集中的一组值对它们进行索引。但是, myTable[c(5,5,5,5)]显然没有做我想要的。我如何c(5,5,5,5)阅读为myTable[5,5,5,5]

4

2 回答 2

3

跟进@ttmaccer 的回答:之所以有效,是因为其中的(稍微)晦涩的段落?"["如下:

When indexing arrays by ‘[’ a single argument ‘i’ can be a
matrix with as many columns as there are dimensions of ‘x’;
the result is then a vector with elements corresponding to
the sets of indices in each row of ‘i’.

使用t(ii)中的效果

ii <- c(5,5,5,5)
a[t(ii)]

是转换ii为一个 1x4 矩阵,[解释为如上所述的矩阵;a[matrix(ii,nrow=1)]会更明确但不那么紧凑。

这种方法的好处(除了避免看起来很神奇的方面do.call)是它可以并行工作于一组以上的索引,如

jj <- matrix(c(5,5,5,5,
               6,6,6,6),byrow=TRUE,nrow=2)
a[jj]
## [1] 4445 5556
于 2012-07-17T21:12:53.383 回答
2

如果我正确理解了您的问题,那么使用 的这个构造do.call()应该可以满足您的要求:

## Create an example array and a variable containing the desired index
a <- array(1:1e4, dim = c(10, 10, 10, 10))
ii <- c(5, 5, 5, 5)

## Use do.call to extract the desired element.
do.call("[", c(list(a), ii))
# [1] 4445

上面的调用有效,因为以下都是等价的:

a[5, 5, 5, 5]
`[`(a, 5, 5, 5, 5)
do.call("[", list(a, 5, 5, 5, 5))
do.call("[", c(list(a), ii))
于 2012-07-17T20:44:21.720 回答