Reputation: 105
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)
Upvotes: 2
Views: 1009
Reputation: 35554
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
Upvotes: 1
Reputation: 269491
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
Upvotes: 2
Reputation: 72693
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
Upvotes: 1