向量化跨矩阵行的操作 [英] Vectorizing which operation across the rows of a matrix
问题描述
我想对矩阵 X
上的 which
操作进行向量化(apply
),如下面的 for
所示> 循环的结果是向量 ind
:
I would like to vectorize (apply
) a which
operation on matrix X
as illustrated by the following for
loop having as result the vector ind
:
X = matrix( 1:20, 4, 5 )
V = sample( 1:20, 4 )
ind = numeric()
for( i in 1:nrow(X) ) ind[i] = max( c(0, which(X[i,] < V[i]) ))
操作在ind
中为X
中的每一行返回最大值小于X
所指示值的元素的索引V
的>-row-对应元素.
The operation returns in ind
for each row in X
the index of the element with the highest value smaller than the value indicated by the X
-row-corresponding element of V
.
操作 max
将所有符合条件的索引的向量映射到一个标量.或者,我会对返回的操作感到满意,例如所有索引的list
(我可以lapply
max
).
The operation max
maps the vector of all eligible indices to a scalar. Alternatively I would by happy with an operation returning e.g. a list
of all indices (to which I can lapply
max
).
推荐答案
如果你的矩阵像你分享的例子一样有递增的值(我当然怀疑),但如果是这样,你可以简单地做,
If your matrix has increasing values like the example you shared (which of course I doubt), but If it does you can simply do,
rowSums(X < V)
#[1] 4 3 4 0
但是,如果不是这种情况,那么简单的 apply
就足够了,即
However, If this is not the case, then a simple apply
will suffice, i.e.
apply(X < V, 1, function(i)max(which(i)))
#[1] 4 3 4 -Inf
记住所有的数学运算都是向量化的,所以<
是向量化的
Remember that all mathematical operations are vectorized, so <
is vectorized
您可以照常替换 -Inf
这篇关于向量化跨矩阵行的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!