i want to subset a 3-dimensional array with three matrices where each matrix represents one dimension.
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)
# A[1,4,1](=1) A[2,2,2](=8)
# A[3,3,2](=10) A[1,1,1](=3)
A(sub2ind(size(A), ind_dimension1, ind_dimension2, ind_dimension3))
sub2ind(size(A2), ind_dimension1, ind_dimension2)
How about this?
myMat <- matrix(A[cbind(c(ind_dimension1), c(ind_dimension2), c(ind_dimension3))], dim(ind_dimension1)) myMat [,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