Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One option is to use <code>outer()</code> to apply the binary operator function <code>&gt;</code> to <code>a</code> and <code>b</code>:</p> <pre><code>&gt; outer(a, b, "&gt;") [,1] [,2] [,3] [,4] [,5] [1,] FALSE FALSE FALSE FALSE FALSE [2,] FALSE FALSE TRUE FALSE TRUE [3,] TRUE FALSE TRUE TRUE TRUE [4,] TRUE FALSE TRUE TRUE TRUE [5,] TRUE TRUE TRUE TRUE TRUE [6,] TRUE TRUE TRUE TRUE TRUE [7,] FALSE FALSE TRUE FALSE TRUE </code></pre> <p>The answer to the Q is then given by the row sums of the result above:</p> <pre><code>&gt; rowSums(outer(a, b, "&gt;")) [1] 0 2 4 4 5 5 2 </code></pre> <p>For this example data set, this solution is slightly faster that <code>findIntervals()</code> but not by much:</p> <pre><code>&gt; system.time(replicate(1000, findInterval(a - 0.5, sort(b)))) user system elapsed 0.131 0.000 0.132 &gt; system.time(replicate(1000, rowSums(outer(a, b, "&gt;")))) user system elapsed 0.078 0.000 0.079 </code></pre> <p>It is also slightly faster than the <code>sapply()</code> version, but marginally:</p> <pre><code>&gt; system.time(replicate(1000, sapply(a, function(x)sum(b&lt;x)))) user system elapsed 0.082 0.000 0.082 </code></pre> <p>@Charles notes that most of the time in the <code>findInterval()</code> example is used by <code>sort()</code>, which can be circumvented via <code>order()</code>. When this is done, the <code>findInterval()</code> solution is faster than the <code>outer()</code> solution:</p> <pre><code>&gt; system.time(replicate(1000, findInterval(a - 0.5, b[order(b)]))) user system elapsed 0.049 0.000 0.049 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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