title: Finding overlap in ranges with R
body: <p>I have two data.frames each with three columns:  chrom, start &amp; stop, let's call them rangesA and rangesB.  For each row of rangesA, I'm looking to find which (if any) row in rangesB fully contains the rangesA row - by which I mean <code>rangesAChrom == rangesBChrom, rangesAStart &gt;= rangesBStart and rangesAStop &lt;= rangesBStop</code>.</p>
  
  <p>Right now I'm doing the following, which I just don't like very much.  Note that I'm looping over the rows of rangesA for other reasons, but none of those reasons are likely to be a big deal, it just ends up making things more readable given this particular solution.</p>
  
  <p>rangesA:</p>
  
  <pre><code>chrom   start   stop
   5       100     105
   1       200     250
   9       275     300
  </code></pre>
  
  <p>rangesB:</p>
  
  <pre><code>chrom    start    stop
    1       200      265
    5       99       106
    9       275      290
  </code></pre>
  
  <p>for each row in rangesA:</p>
  
  <pre><code>matches &lt;- which((rangesB[,'chrom']  == rangesA[row,'chrom']) &amp;&amp;
                   (rangesB[,'start'] &lt;= rangesA[row, 'start']) &amp;&amp;
                   (rangesB[,'stop'] &gt;= rangesA[row, 'stop']))
  </code></pre>
  
  <p>I figure there's got to be a better (and by better, I mean faster over large instances of rangesA and rangesB) way to do this than looping over this construct.  Any ideas?</p>