我有不同大小的列联表。我想使用数据集中的一组值对它们进行索引。然而,myTable[c(5,5,5,5)]显然没有做我想要的事情。如何让c(5,5,5,5)读取为myTable[5,5,5,5]
发布于 2012-07-18 05:12:53
跟进@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-18 04:44:22
如果我正确理解了您的问题,那么这个使用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))https://stackoverflow.com/questions/11530241
复制相似问题