rmatrixsubsetindicespicking

R: Picking values from matrix by indice matrix


I have a datamatrix with n rows and m columns (in this case n=192, m=1142) and an indice matrix of nxp (192x114). Each row of the indice matrix shows the column numbers of the elements that I would like to pick from the matching row of the datamatrix. Thus I have a situation something like this (with example values):

data<-matrix(1:30, nrow=3)
data
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    4    7   10   13   16   19   22   25    28
[2,]    2    5    8   11   14   17   20   23   26    29
[3,]    3    6    9   12   15   18   21   24   27    30


columnindices<-matrix(sample(1:10,size=9, replace=TRUE),nrow=3)
columnindices
      [,1] [,2] [,3]
[1,]    8    7    4
[2,]   10    8   10
[3,]    8   10    2

I would like to pick values from the datamatrix rows using the in columnindices matrix, so that the resulting matrix would look like this

      [,1] [,2] [,3]
[1,]   22   19   10
[2,]   29   23   29
[3,]   24   30   6

I tried using a for loop:

result<-0
for(i in 1:3) {
 result[i]<-data[i,][columnindices[,i]]
 print[i]
}

but this doesn't show the wished result. I guess my problem should be rather simply solved, but unfortunately regardless many hours of work and multiple searches I still haven't been able to solve it (I am rookie). I would really appreciate some help!


Solution

  • Your loop is just a little bit off:

    result <- matrix(rep(NA, 9), nrow = 3)
    for(i in 1:3){
      result[i,] <- data[i, columnindices[i,]]
    }
    
    > result
         [,1] [,2] [,3]
    [1,]   25   13    7
    [2,]   29   29   23
    [3,]   15   15   18
    

    Note that the matrix is not exactly the one you posted as expected result because the code for your example columnindices does not match the matrix you posted below. Code should work as you want it.