2012-11-14 169 views
4

我對R中的多維數組有一個簡單的數組索引問題。我做了大量的模擬,每個模擬都給出了矩陣的結果,其中條目被分類爲類別。因此,例如,結果看起來像多維數組的R數組索引

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

現在我想我的實驗結果存儲在一個三維矩陣,其中前兩個尺寸是相同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使用值作爲指標。

我該怎麼做,而不使用循環?

+0

您可能正在從'abind'軟件包中尋找'abind'。 –

回答

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 
+0

啊,非常感謝,工作正常:) –