Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R array indexing for multi-dimensional arrays

I have a simple array indexing question for multi-dimensional arrays in R. I am doing a lot of simulations that each give a result as a matrix, where the entries are classified into categories. So for example a result looks like

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

Now I want to store the results of my experiments in a 3D-matrix, where the first two dimension are the same as in aresult and the third dimension holds the number of experiments that fell into each category. So my arrays of counts should look like

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

and after each experiment I want to increment the numbers in the third dimension by 1, using the values in aresults as indexes.

How can I do that without using loops?

like image 200
Bärbel Avatar asked Nov 03 '22 11:11

Bärbel


1 Answers

This sounds like a typical job for matrix indexing. By subsetting Counts with a three column matrix, each row specifying the indices of an element we want to extract, we are free to extract and increment any elements we like.

# 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
like image 71
Backlin Avatar answered Nov 09 '22 14:11

Backlin