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