2014-03-18 47 views
1

我有一个row vector和一个column vector说c(1,2),c(7,100)。我想提取(1,7),(2,100)。一次从R中的矩阵中选择元素

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

我该怎么办?

+1

我会读'?矩阵和'?'[' ' –

回答

2

您可以使用内部[ 2列子集矩阵:

mx <- matrix(1:200, nrow=2) 
mx[cbind(c(1, 2), c(7, 100))] 

生产:

[1] 13 200 
5

你想利用这个功能,如果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’. 

下面是一个例子

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 
+0

太棒了!惊人! – user3341953