【发布时间】:2014-03-18 20:33:46
【问题描述】:
我有一个 row vector 和一个 column vector 说 c(1,2), c(7,100)。我想提取 (1,7), (2,100)。
我发现Matrix[row, column] 会返回一个叉积,而不仅仅是两个数字的向量。
我该怎么办?
【问题讨论】:
-
我会读
?matrix和?'['
我有一个 row vector 和一个 column vector 说 c(1,2), c(7,100)。我想提取 (1,7), (2,100)。
我发现Matrix[row, column] 会返回一个叉积,而不仅仅是两个数字的向量。
我该怎么办?
【问题讨论】:
?matrix 和 ?'['
您想利用以下功能:如果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
【讨论】:
您可以在 [ 中使用 2 列子集矩阵:
mx <- matrix(1:200, nrow=2)
mx[cbind(c(1, 2), c(7, 100))]
产生:
[1] 13 200
【讨论】: