0

I'm trying to get the value of a matrix with a vector of row indexes and column indexes like this.

M = matrix(rnorm(100),nrow=10,ncol=10)
set.seed(123)
row_index = sample(10) # 3  8  4  7  6  1 10  9  2  5
column_index = sample(10) # 10  5  6  9  1  7  8  4  3  2

Is there any way I can do something like

M[row_index, column_index]

and get the values for

M[3,10], M[8,5], ...

as a vector?

Sotos
  • 51,121
  • 6
  • 32
  • 66
Shota Shimizu
  • 121
  • 2
  • 8

2 Answers2

1

We need a cbind to create a 2 column matrix where the first column denotes row index and second column index

M[cbind(row_index, column_index)]
akrun
  • 874,273
  • 37
  • 540
  • 662
0

The solution I present is not the best way of doing things in R, because in most cases for loops are slow compared to vectorized operations. However, for the problem you can simply implement a loop to index the matrix. While there might be absolutely no reason at all to not specify any object that provide the data structure(such as a data-frame or a matrix), we can avoid it anyway using a loop construct.

for (i in 1:length(row_index)) {
 print(M[row_index[i], column_index[i]])
  }
dd_rookie
  • 331
  • 2
  • 3
  • 13