0

Say you have the following matrix:

mat <- matrix(1:12, nrow = 3, ncol = 4)
print(mat)
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

And you wish to extract values from the matrix with the following row and column indices:

rowind <- c(2,3,1)
colind <- c(4,4,1)

So I'm looking for the values 11 (row 2, col 4), 12 (row 3, col 4) and 1 (row 1, col 1).

If I try passing the column and row vectors into the matrix with:

mat[rowind, colind]

I get a new matrix where all permutations of rowind and colind are included:

     [,1] [,2] [,3]
[1,]   11   11    2
[2,]   12   12    3
[3,]   10   10    1

How I can instead get the values relating only to the specific row and column combinations? I considered using a for loop but given my matrix and index vectors are large I feel this would be unnecessarily slow and that there is very likely a better way.

Will T-E
  • 607
  • 1
  • 7
  • 16

1 Answers1

1

We can cbind the indices to extract the values

mat[cbind(rowind, colind)]
#[1] 11 12  1
akrun
  • 874,273
  • 37
  • 540
  • 662