Mollifier - 10 months ago 42
R Question

# Subsetting multi-dim. array with matrices

i want to subset a 3-dimensional array with three matrices where each matrix represents one dimension.
An example:

``````    set.seed(1)
A = array(sample(1:10,24, replace=TRUE), dim=c(3,4,2))

ind_dimension1 = matrix(c(1,3,2,1), nrow=2)
ind_dimension2 = matrix(c(4,3,2,1), nrow=2)
ind_dimension3 = matrix(c(1,2,2,1), nrow=2)
``````

As result i want a matrix with the same dimension as the subsetting matrices, i.e. 2x2:

``````    # A[1,4,1](=1)    A[2,2,2](=8)
# A[3,3,2](=10)   A[1,1,1](=3)
``````

In Matlab this can be done by:

``````    A(sub2ind(size(A), ind_dimension1, ind_dimension2, ind_dimension3))
``````

With two dimensions, i.e.
`A2=A[,,1]`
, the Matlab command
`sub2ind(size(A2), ind_dimension1, ind_dimension2)`
can be replicated in R with
`(ind_dimension2-1)*dim(A2)[2]+ind_dimension1`
as mentioned by Hiebeler (2010) https://cran.r-project.org/doc/contrib/Hiebeler-matlabR.pdf (Page 5). This is not possible in higher dimensions.

``````myMat <- matrix(A[cbind(c(ind_dimension1),
This uses matrix subsetting (see `help("[")`) to extract the desired elements. The dimension matrices are turned into vectors with `c`, and then recombined into a matrix with `cbind` that is used to extract from the array. The resulting vector is fed to `matrix` and the desired dimensions are produces with `dim`.