Sara - 9 months ago 53
R Question

# R: extract matrix from array, using a matrix of indices

I´m coding in R and I have a 3 dimensional array that contains data (ab in the example). Then I have a matrix that contains indices of the 3rd array dimension (idx). This matrix has the same number of rows and columns of the array. I want to use the indices contained in idx to extract data from the array, to get a matrix with same dimension of idx. Please see the example below:

``````a <- c(1:9)
b <- rev(a)

#array of data
ab <- array(c(a,b), dim = c(3,3,2))
ab
, , 1

[,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

, , 2

[,1] [,2] [,3]
[1,]    9    6    3
[2,]    8    5    2
[3,]    7    4    1

#matrix of indices
idx <- matrix(sample(1:2,9,replace=TRUE), nrow = 3)
idx
[,1] [,2] [,3]
[1,]    2    2    2
[2,]    2    1    1
[3,]    1    1    1

#now I want to get the following matrix:
[,1] [,2] [,3]
[1,]    9    6    3
[2,]    8    5    8
[3,]    3    6    9

#these two don´t do the job
ab[idx]
ab[ , ,idx]
``````

Does anybody know how can I get that?

Many thanks!

Sara

We need an index for row/column and the third dimension (from 'idx') to extract the elements. We do this by `cbind`ing the row index, column index with the 'idx'.
``````i1 <- dim(ab)[1]