Home > OS >  How to select elements of a matrix given a vector with same number of columns?
How to select elements of a matrix given a vector with same number of columns?

Time:02-15

I have a matrix with 5 rows and 4 columns and a vector with 4 elements. I want to extract the 4 elements in the matrix where the corresponding vector value is the row index of that matrix element.

Here is my data:

mat1.data <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
mat1 <- matrix(mat1.data,nrow=5,ncol=4,byrow=TRUE)
mat1

vec1<-c(4,2,5,1)

The output I am trying to get to is:

c(13,6,19,4)

CodePudding user response:

We can construct a matrix of row/column indexes to extract. The column sequence can be seq_len(ncol

mat1[cbind(vec1, seq_len(ncol(mat1)))]
[1] 13  6 19  4

Or another option is to extract the rows and use diag

diag(mat1[vec1,])
[1] 13  6 19  4

CodePudding user response:

Another base R option using mapply asplit (but not as efficient as diag solution by @akrun)

> mapply(`[[`, asplit(mat1, 2), vec1)
[1] 13  6 19  4
  • Related