2012-07-17 50 views
6

我有不同大小的应变表。我想使用数据集中的一组值对它们编制索引。但是, myTable[c(5,5,5,5)]显然不会做我想要的。如何获得c(5,5,5,5)读为myTable[5,5,5,5]使用列向量索引多维表

回答

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转换为1×4矩阵,其[解释作为基质如上所述; 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 
+0

感谢扩大对@ ttmacer的答案。非常好。 – 2012-07-17 21:21:47

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))