Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

Vectorizing which operation across the rows of a matrix

$
0
0

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


Viewing all articles
Browse latest Browse all 201945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>