我对R中的多维数组有一个简单的数组索引问题。我正在做很多模拟,每个模拟都给出一个结果作为矩阵,其中将条目分类。因此,例如结果看起来像

aresult<-array(sample(1:3, 6, replace=T), dim=c(2,5),
               dimnames=list(
                 c("prey1", "prey2"),
                 c("predator1", "predator2", "predator3", "predator4", "predator5")))

现在,我想将实验结果存储在3D矩阵中,其中前两个维与aresult中的维相同,第三个维包含属于每个类别的实验数。所以我的数列应该看起来像
Counts<-array(0, dim=c(2, 5, 3),
              dimnames=list(
                c("prey1", "prey2"),
                c("predator1", "predator2", "predator3", "predator4", "predator5"),
                c("n1", "n2", "n3")))

在每次实验之后,我都想使用aresults中的值作为索引,将第三维的数字增加1。

如何不使用循环就可以做到这一点?

最佳答案

这听起来像是矩阵索引的典型工作。通过用三列矩阵替换Counts,每行指定我们要提取的元素的索引,我们可以自由提取和递增我们喜欢的任何元素。

# Create a map of all combinations of indices in the first two dimensions
i <- expand.grid(prey=1:2, predator=1:5)

# Add the indices of the third dimension
i <- as.matrix( cbind(i, as.vector(aresult)) )

# Extract and increment
Counts[i] <- Counts[i] + 1

关于多维数组的R数组索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13379540/

10-12 22:12
查看更多