R - 如何通过索引向量获取多维数组的值

标签 r

假设我有一个名为 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 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.

你可以简单地做:

pi[matrix(indexes, 1)]

关于R - 如何通过索引向量获取多维数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865337/

相关文章:

regex - 在第一个遇到的数字上通过 dplyr 使用单独的 (tidyr) 分隔列

r - 如何绕过R中的for循环中的错误?

r - 在R中使用plotly在轴标题中换行和下标

python - 可以像普通 R 代码一样从 knitr block 将 Python 代码发送到 RStudio 控制台吗?

oop - 答: 什么是老虎机?

r - 嵌套 ifelse R 函数传递给 sapply() 以创建新的 data.frame

r - R 中的高效分块时间序列

R计算每行出现的次数非常慢

r - 抑制R中nnet multinom函数中的收敛消息

r - ggplot2 直方图 scale_fill_gradient 不适用于连续变量