Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

c(13,6,19,4)

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading