R: extract matrix from array using index matrix

I am coding in R, and I have a three-dimensional array containing data (ab in the example). Then I have a matrix containing indices of the 3rd dimension of the array (idx). This matrix has the same number of rows and columns in an array. I want to use the indices contained in idx to retrieve data from an array to get a matrix with the same idx size. 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 anyone know how I can get this?

Many thanks!

Sarah

+4
source share
2 answers

/ ( 'idx') . cbind , "idx".

i1 <- dim(ab)[1]
j1 <- dim(ab)[2]
matrix(ab[cbind(rep(seq_len(i1),  j1),rep(seq_len(j1), each = i1), c(idx))], ncol=3)
#     [,1] [,2] [,3]
#[1,]    9    6    3
#[2,]    8    5    8
#[3,]    3    6    9
+3

, : idx:

        [,1] [,2] [,3]
[1,]    2    2    1
[2,]    1    2    1
[3,]    2    2    2

:

idVec <- as.vector(idx)
d3mat <- apply(ab,3,as.vector)

:

len <- length(idVec)
len <- 1:len

len:

resultvec <- sapply(len, function(x, vec, mat){return(mat[x,vec[x]])}, mat=d3mat, vec=idVec)

:

    matrix(resultVec,3,3)
     [,1] [,2] [,3]
[1,]    9    6    7
[2,]    2    5    8
[3,]    7    4    1
+1

Source: https://habr.com/ru/post/1653764/


All Articles