快速访问矩阵元素,其中索引由其他矩阵给出

时间:2019-04-30 16:12:43

标签: r matrix

我得到了一个矩阵M。我现在需要确定一个相同维度的矩阵,该矩阵由

定义

N_{i,j} = M_{A(i,j),B(i,j)}

对于相同维度的两个矩阵AB,它们定义了索引。

例如,

set.seed(1)
M <- matrix(LETTERS[1:(4*6)], ncol=6)
A <- matrix(sample(c(1:4), 4*6, replace=TRUE), ncol=6)
B <- matrix(sample(c(1:6), 4*6, replace=TRUE), ncol=6)

我现在如何快速确定N

1 个答案:

答案 0 :(得分:2)

尝试一下:

                    dog                   cat                   monkey
0  The dog is beautiful  The cat is beautiful  The monkey is beautiful

replace(M, TRUE, M[cbind(c(A), c(B))])