简体   繁体   中英

Subsetting a matrix with another matrix in R

I have two matrices, one with values of interest and the other with indices corresponding to columns in the first. The code below does what I want but it will need to be run on much larger matrices and many many times. My gut tells me there might be a faster way to accomplish this so any thoughts would be appreciated.

set.seed(0)
y = matrix(runif(20), 4, 5)
idx = matrix(sample(1:5, 12, replace = T), 4, 3)
z = lapply(1:nrow(y), function(i) y[i, idx[i,]])
z = do.call(rbind, z)

1) Create a two column matrix whose elements are the row number and idx value for each entry in idx and subscript y by it. Then reshape back to the dimensions of idx .

matrix(y[cbind(c(row(idx)), c(idx))], nrow(idx))

2) A variation of that is:

zz <- idx
zz[] <- y[cbind(c(row(idx)), c(idx))]

# check that result is the same as z in question
identical(zz, z)
## [1] TRUE

Transpose y and adjust the indices in idx .

array(t(y)[idx + (1:nrow(y) - 1) * ncol(y)], dim(idx))

#           [,1]      [,2]      [,3]
# [1,] 0.8966972 0.8966972 0.9082078
# [2,] 0.7176185 0.7176185 0.2655087
# [3,] 0.9919061 0.9919061 0.3841037
# [4,] 0.5728534 0.9446753 0.5728534

You could convert matrix and indices to vectors, subset, an rebuild the matrix.

matrix(as.vector(t(y))[as.vector(t(idx+(1:(nrow(y))-1)*ncol(y)))],nrow(y),b=T)
#           [,1]      [,2]      [,3]
# [1,] 0.8966972 0.8966972 0.9082078
# [2,] 0.7176185 0.7176185 0.2655087
# [3,] 0.9919061 0.9919061 0.3841037
# [4,] 0.5728534 0.9446753 0.5728534

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM