5

我对 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 矩阵中,其中前两个维度与 in 相同,aresult第三个维度包含属于每个类别的实验数量。所以我的计数数组应该看起来像

Counts<-array(0, dim=c(2, 5, 3), 
              dimnames=list(
                c("prey1", "prey2"), 
                c("predator1", "predator2", "predator3", "predator4", "predator5"),
                c("n1", "n2", "n3")))

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

我怎么能不使用循环来做到这一点?

4

1 回答 1

2

这听起来像是矩阵索引的典型工作。通过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
于 2012-11-14T13:41:51.093 回答