我有两个矩阵,一个具有感兴趣的值,另一个具有与第一个列对应的索引。下面的代码实现了我想要的功能,但需要在更大的矩阵上运行很多次。我的直觉告诉我,可能会有更快的方法来完成此操作,因此任何想法都会受到赞赏。
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)
答案 0 :(得分:2)
1)创建一个两列矩阵,其元素分别是idx
和下标idx
中每个条目的行号和y
值。然后重新调整为idx
的尺寸。
matrix(y[cbind(c(row(idx)), c(idx))], nrow(idx))
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
答案 1 :(得分:1)
转置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
答案 2 :(得分:1)
您可以将矩阵和索引转换为向量,子集,然后重新构建矩阵。
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