Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just a add-on note: if you know the range of the values for each vector, then it might be quicker to calculate the max and mins first, e.g.</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 } f &lt;- function(a, b) { # set up vars a.length &lt;- length(a) b.length &lt;- length(b) b.sorted &lt;- b[order2(b)] b.min &lt;- b.sorted[1] b.max &lt;- b.sorted[b.length] results &lt;- integer(a.length) # pre-process minimums v.min &lt;- which(a &lt;= b.min) # pre-process maximums v.max &lt;- which(a &gt; b.max) results[v.max] &lt;- b.max # compare the rest ind &lt;- c(v.min, v.max) results[-ind] &lt;- findInterval2(a[-ind] - 0.5, b.sorted) results } </code></pre> <p>Which gives the following timeings</p> <pre><code>&gt; N &lt;- 10 &gt; n &lt;- 1e5 &gt; b &lt;- runif(n, 0, 100) &gt; a &lt;- runif(n, 40, 60) # NB smaller range of values than b &gt; summary( replicate(N, system.time(findInterval2(a - 0.5, b[order2(b)]))[3]) ) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.0300 0.0300 0.0400 0.0390 0.0475 0.0500 &gt; summary( replicate(N, system.time(f(a, b))[3]) ) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.010 0.030 0.030 0.027 0.030 0.040 </code></pre> <p>However, if you don't know the ranges ahead of time, or can't make an educated guess about them, then this would probably be slower.</p>
 

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