title: Overlapping Genomic Ranges
body: <p>I have two files</p>
  
  <p>encode</p>
  
  <pre><code>X.pattern.name       chr       start    stop    strand  score   p.value q.value matched.sequence
  1   V_CETS1P54_01   chr1    98769545    98769554    +   11.42280    8.89e-05    NA  TCAGGATGTA
  2   V_CETS1P54_01   chr1    152013037   152013046   +   11.98020    4.74e-05    NA  ACAGGAAGTT
  3   V_CETS1P54_01   chr1    168932563   168932572   +   11.60860    7.59e-05    NA  ACCGGATGCT
  </code></pre>
  
  <p>encode.total</p>
  
  <pre><code>    chr     start           stop
  1   chr1    58708485    58708713
  2   chr1    58709084    58710538
  3   chr1    98766295    98766639
  4   chr1    98766902    98770338
  5   chr1    107885506   107889414
  6   chr1    138589531   138590856
  7   chr1    138591180   138593378
  8   chr1    152011746   152013185
  9   chr1    152014263   152014695
  10  chr1    168930561   168933076
  11  chr1    181808064   181808906
  12  chr1    184609002   184611519
  13  chr1    193288453   193289567
  14  chr1    193290105   193290490
  15  chr1    193290744   193291092
  16  chr1    196801920   196804954
  </code></pre>
  
  <p>I want to compare the two files, each entry by <strong>chr</strong>, <strong>start</strong> and <strong>stop</strong>. If the start and stop values in first file falls between the start and stop of the second file for the same chromosome, then that start &amp; stop values in the first file should be replaced by the second file's start &amp; stop values. I have written a for loop for that purpose but it is taking too long. What are the alternatives?</p>
  
  <p>Code:</p>
  
  <pre><code>for(i in 1:nrow(encode))
  {
       for(j in 1:nrow(encode.total))
       {
             if(encode[i,2]==encode.total[j,1])
             {
                 if((encode[i,3]&gt;=encode.total[j,2]) &amp; (encode[i,4]&lt;=encode.total[j,3]))
                 {
                     encode[i,3]=encode.total[j,2]
                     encode[i,4]=encode.total[j,3]
                 }
             }
       }
  }
  </code></pre>
  
  <p>For the same purpose I also tried the GenomicRanges package like below. The size of my dataframes is huge and the merge function on them creates a VERY LARGE dataframe (>2 billion rows which is not allowed), although I eventually subset the dataframe in a smaller one. But merge() is taking a LOT of memory and terminating R.</p>
  
  <pre><code>gr1&lt;-GRanges(seqnames=encode$chr,IRanges(start=encode$start,end=encode$end))
  gr2&lt;-GRanges(seqnames=encode.total$chr, IRanges(start=encode.total$start,end=encode.total$end))
  
  ranges &lt;- merge(as.data.frame(gr1),as.data.frame(gr2),by="seqnames",suffixes=c("A","B"))
  ranges &lt;- ranges[with(ranges, startB &lt;= startA &amp; endB &gt;= endA),]
  </code></pre>