Bär*_*bel 5 r multidimensional-array
我对R中的多维数组有一个简单的数组索引问题。我正在做很多模拟,每个模拟都给出一个矩阵形式的结果,其中将条目分类。例如,结果看起来像
aresult<-array(sample(1:3, 6, replace=T), dim=c(2,5),
dimnames=list(
c("prey1", "prey2"),
c("predator1", "predator2", "predator3", "predator4", "predator5")))
Run Code Online (Sandbox Code Playgroud)
现在,我想将实验结果存储在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")))
Run Code Online (Sandbox Code Playgroud)
在每个实验之后,我都希望将三维中的数字增加1,并使用中的值aresults作为索引。
不使用循环怎么办?
这听起来像是矩阵索引的典型工作。通过使用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
Run Code Online (Sandbox Code Playgroud)