Home > Blockchain >  R using vector as an index in a matrix
R using vector as an index in a matrix

Time:11-03

I have these two objects:

Vec<-c(1,3,2)
Matrix<-rbind(c(4,2,3,0),c(2,9,1,0),c(2,2,9,9))

For each row of the matrix I would like to use the corresponding value from Vec as an index to pull out the value from the matrix. E.g. for the first row c(4,2,3,0) I want to pick out the first element (4), for the second row c(2,9,1,0) I would like to pick out the third (1).

The result I would like is:

Result<-c(4,1,2)

CodePudding user response:

We may need the row index to create a matrix by cbinding to extract the element based on the row/column index

 Matrix[cbind(seq_len(nrow(Matrix)), Vec)]
[1] 4 1 2

Or another option is

mapply(`[`, asplit(Matrix, 1), Vec)
[1] 4 1 2

CodePudding user response:

We can also use linear indexing

> t(Matrix)[Vec   ncol(Matrix) * (seq_along(Vec) - 1)]
[1] 4 1 2

CodePudding user response:

With diag:

diag(Matrix[seq_along(Vec), Vec])
#[1] 4 1 2

CodePudding user response:

Similar logic to ThomasIsCoding's but skipping the transpose:

n = nrow(Vec)
stopifnot(n == length(Vec))
Matrix[1:n   n * (Vec - 1)]
# [1] 4 1 2
  • Related