向量化跨矩阵行的操作 [英] Vectorizing which operation across the rows of a matrix

查看:33
本文介绍了向量化跨矩阵行的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对矩阵 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆