假设我有一个名为 pi
的多维数组,并且直到运行时才知道它的维数:
dims <- rep(3, dim_count)
pi <- array(0, dims)
如您所见,维度计数取决于 dim_count
。当我有索引向量时,如何从数组中检索值?例如当我有:
dim_count <- 5
indexes <- c(1, 2, 3, 3, 3)
我要找回
pi[1, 2, 3, 3, 3]
有没有一种简短、有效且优雅的方法来做到这一点?
最佳答案
利用[
的鲜为人知的用法:
When indexing arrays by
[
a single argumenti
can be a matrix with as many columns as there are dimensions ofx
; the result is then a vector with elements corresponding to the sets of indices in each row ofi
.
你可以简单地做:
pi[matrix(indexes, 1)]
关于R - 如何通过索引向量获取多维数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865337/