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
Use a row/column indexing by cbind
ing with row sequence
mymatrix[cbind(seq_len(nrow(mymatrix)), mycols)]
[1] 2 6 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With