[英]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. 1)创建一个两列矩阵,其元素是
idx
和下标y
每个条目的行号和idx
值。 Then reshape back to the dimensions of idx
.然后重塑回
idx
的尺寸。
matrix(y[cbind(c(row(idx)), c(idx))], nrow(idx))
2) A variation of that is: 2)它的一个变体是:
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
.转置
y
并调整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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.