title: R count values of a vector in ranges given by two other vectors
body: <p>R:   Assume  </p>
  
  <pre><code>length(v)=n length(a)=m=length(b), 
  n and m are large;
  v, a, b may contain NA or NaN's;  
  a not necessarily smaller than b.
  </code></pre>
  
  <p>How to find the number of such pairs of indices i j that   </p>
  
  <pre><code>a[j] &lt; v[i] &lt; b[j]
  </code></pre>
  
  <p>How to find the number of such (i,j) that either </p>
  
  <pre><code>a[j] &lt; v[i] &lt; b[j] or a[j] &gt; v[i] &gt; b[j]
  </code></pre>
  
  <p>This seems to be too slow:</p>
  
  <pre><code>sumrange &lt;- function(v,ma)
  {
    s &lt;- 0
    for(i in 1:length(v))
    {
      s &lt;- s + sum(v[i] &gt; ma[,1] &amp; ma[,2] &gt; v[i], na.rm = TRUE)
    }
    s
  }  
  result &lt;- sumrange(v, cbind(a, b))
  </code></pre>
  
  <p>EDIT: @DatamineR</p>
  
  <pre><code>a&lt;-c(1,6,4,2,NA)
  b&lt;-c(5,4,0,7,0)
  v&lt;-c(3,5)
  </code></pre>
  
  <p>possible pairs in question 1: </p>
  
  <pre><code>1&lt;3&lt;5 (1,1)
  2&lt;3&lt;7 (1,4)
  2&lt;5&lt;7 (2,4)
  </code></pre>
  
  <p>result=3</p>
  
  <p>possible pairs in question 2:  all the above and </p>
  
  <p>6>5>4  (2,2)</p>
  
  <p>result =3+1=4</p>
  
  <p>EDIT:
  Actually it works better is one first drops the NA's </p>
  
  <pre><code>vc&lt;-na.omit(v)
  ma&lt;-na.omit(cbind(a,b))
  result&lt;-sumrange(vc,ma)
  </code></pre>