Mollifier Mollifier - 3 months ago 20
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:

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.
, the Matlab command
sub2ind(size(A2), ind_dimension1, ind_dimension2)
can be replicated in R with
as mentioned by Hiebeler (2010) (Page 5). This is not possible in higher dimensions.

Thanks in advance.

lmo lmo

How about this?

myMat <- matrix(A[cbind(c(ind_dimension1), 

     [,1] [,2]
[1,]    1    8
[2,]   10    3

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.