Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try this:</p> <pre><code>findInterval(a - 0.5, sort(b)) </code></pre> <hr> <p>Speed improvement from a) avoiding <code>sort</code>, and b) avoiding overhead in <code>findInterval</code> and <code>order</code> by using simpler <code>.Internal</code> wrappers:</p> <pre><code>order2 = function(x) .Internal(order(T, F, x)) findInterval2 = function(x, vec, rightmost.closed=F, all.inside=F) { nx &lt;- length(x) index &lt;- integer(nx) .C('find_interv_vec', xt=as.double(vec), n=length(vec), x=as.double(x), nx=nx, as.logical(rightmost.closed), as.logical(all.inside), index, DUP = FALSE, NAOK=T, PACKAGE='base') index } &gt; system.time(for (i in 1:10000) findInterval(a - 0.5, sort(b))) user system elapsed 1.22 0.00 1.22 &gt; system.time(for (i in 1:10000) sapply(a, function(x)sum(b&lt;x))) user system elapsed 0.79 0.00 0.78 &gt; system.time(for (i in 1:10000) rowSums(outer(a, b, "&gt;"))) user system elapsed 0.72 0.00 0.72 &gt; system.time(for (i in 1:10000) findInterval(a - 0.5, b[order(b)])) user system elapsed 0.42 0.00 0.42 &gt; system.time(for (i in 1:10000) findInterval2(a - 0.5, b[order2(b)])) user system elapsed 0.16 0.00 0.15 </code></pre> <p>The complexity of defining <code>findInterval2</code> and <code>order2</code> is probably only warranted if you have heaps of iterations with fairly small N.</p> <p>Also timings for larger N:</p> <pre><code>&gt; a = rep(a, 100) &gt; b = rep(b, 100) &gt; system.time(for (i in 1:100) findInterval(a - 0.5, sort(b))) user system elapsed 0.01 0.00 0.02 &gt; system.time(for (i in 1:100) sapply(a, function(x)sum(b&lt;x))) user system elapsed 0.67 0.00 0.68 &gt; system.time(for (i in 1:100) rowSums(outer(a, b, "&gt;"))) user system elapsed 3.67 0.26 3.94 &gt; system.time(for (i in 1:100) findInterval(a - 0.5, b[order(b)])) user system elapsed 0 0 0 &gt; system.time(for (i in 1:100) findInterval2(a - 0.5, b[order2(b)])) user system elapsed 0 0 0 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload