Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting a matrix in R using array of locations? [duplicate]

Tags:

r

matrix

subset

In R, I would like to subset a matrix by using an array that contains locations. For example, if I had this matrix

mymatrix <- matrix(c(1,2,3,4,5,6,7,8,9),ncol=3,byrow=TRUE)

I would like to be able to return an array that has the values found in columns

mycols <- c(2,3,2)

But mymatrix[,mycols] returns a 3x3 matrix and not the result I would like, namely

c(2,6,8)

Google and "subset" don't seem to be helping me. Can anyone point me in the right direction? Thx, mconsidine

like image 709
mconsidine Avatar asked Jan 24 '23 06:01

mconsidine


1 Answers

Use a row/column indexing by cbinding with row sequence

mymatrix[cbind(seq_len(nrow(mymatrix)), mycols)]
[1] 2 6 8
like image 72
akrun Avatar answered Feb 06 '23 20:02

akrun