Subsetting a matrix in R using array of locations?

Viewed 51

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

3 Answers

Use a row/column indexing by cbinding with row sequence

mymatrix[cbind(seq_len(nrow(mymatrix)), mycols)]
[1] 2 6 8

Another base R option using mapply + asplit

> mapply(`[`, asplit(mymatrix, 1), mycols)
[1] 2 6 8

We could use mapply in this way:

myrows <- 1:nrow(mymatrix)
mycols <- c(2,3,2)

mapply(function(i, j) mymatrix[i,j], myrows, mycols)
[1] 2 6 8
Related