一次从R中的矩阵中选择元素

use*_*953 1 r vector matrix

我有一个row vector和一个column vector说c(1,2),c(7,100).我想提取(1,7),(2,100).

出来,我发现Matrix[row, column]将返回一个跨产品的东西,而不仅仅是两个数字的向量.

我该怎么办?

Rei*_*son 5

您希望利用if m是包含所需行/列索引的矩阵的功能,然后通过传递m作为参数i的子集来[给出所需的行为.从?'['

i, j, ...: indices specifying elements to extract or replace.

          .... snipped ....

          When indexing arrays by ‘[’ a single argument ‘i’ can be a
          matrix with as many columns as there are dimensions of ‘x’;
          the result is then a vector with elements corresponding to
          the sets of indices in each row of ‘i’.
Run Code Online (Sandbox Code Playgroud)

这是一个例子

rv <- 1:2
cv <- 3:4
mat <- matrix(1:25, ncol = 5)

mat[cbind(rv, cv)]

R> cbind(rv, cv)
     rv cv
[1,]  1  3
[2,]  2  4
R> mat[cbind(rv, cv)]
[1] 11 17
Run Code Online (Sandbox Code Playgroud)