矢量化矩阵行中的哪个操作

问题描述 投票:1回答:1

我想对矩阵apply上的which操作进行矢量化(X,如以下for循环所示,其结果是矢量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中具有最高值的元素的索引,该元素的索引小于XV行对应元素所指示的值。

max操作将所有符合条件的索引的向量映射到标量。或者,我会对操作返回例如所有索引的list(我可以将其apply max指向)。

r vectorization which
1个回答
1
投票

这是一个简单的示例

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]) ))

mymax = function(matrix, sample) {
    whichlist = which(matrix < sample)
    max(0, whichlist)
}
ind2 = unlist(lapply(1:nrow(X), function(r) mymax(X[r,], V[r])))

identical(ind, ind2)
# [1] TRUE
© www.soinside.com 2019 - 2024. All rights reserved.