Note that there are some explanatory texts on larger screens.

plurals
  1. POOptimal method of comparing a vector of numbers to values in another vector
    primarykey
    data
    text
    <p>Suppose I have two vectors of values:</p> <pre><code>a &lt;- c(1,3,4,5,6,7,3) b &lt;- c(3,5,1,3,2) </code></pre> <p>And I want to apply some function, <code>FUN</code>, to each of the inputs of <code>a</code> against the whole of <code>b</code>, what's the most efficient way to do it.</p> <p>More specifically, in this case for each of the elements in <code>a</code> I want to know for each value of 'a', how many of the elements in <code>b</code> are greater than or equal to that value. The naïve approach is to do the following:</p> <pre><code>sum(a &lt; b) </code></pre> <p>Of course, this doesn't work as it attempts to iterate over each of the vectors in parallel and gives me the warning: </p> <blockquote> <p>longer object length is not a multiple of shorter object length </p> </blockquote> <p>The output, btw, of that command is <code>3</code>.</p> <p>However, in my situation, what I'd like to see is an output that is:</p> <pre><code>0 2 4 4 5 5 2 </code></pre> <p>Of course, I realize I can do it using a for loop as such:</p> <pre><code>out &lt;- c() for (i in a) { for (i in a) { out[length(out) + 1] = sum(b&lt;i)} } </code></pre> <p>Likewise, I could use <code>sapply</code> as such:</p> <pre><code>sapply(a, function(x)sum(b&lt;x)) </code></pre> <p>However, I'm trying to be a good R programmer and stay away from for loops and <code>sapply</code> seems to be very slow. Are there other alternatives?</p> <p>For what it's worth, I'm doing this a couple of million times where <code>length(b)</code> is always less than <code>length(a)</code> and <code>length(a)</code> ranges from 1 to 30.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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