title: merge 2 genome files based on overlap
body: <p>I have two "BED" files. Each one specifies a set of regions in the genome (start and end columns) and each of these files specify features for the given genomic regions (e.g. the NRL and the other returns the 'mappability' of these regions)</p>
  
  <p>they are organised as follows: </p>
  
  <pre><code>head(file1)
     chr   start     end  mappability
    chr1 3000066 3000100       1.0000
    chr1 3000100 3000130       0.5000
    chr1 3000130 3000199       0.0625
    chr1 3000199 3000277       0.0500
  
  
  head(file2)
     chr   start     end  NRL
    chr1 3000000 3000067  250
    chr1 3000067 3000079  300
    chr1 3000079 3000084  200
    chr1 3000084 3000099  130
  </code></pre>
  
  <p>The problem being that these files are resultant of different experiments and not all of the regions that are documented between the two files overlap... hence I need to find out which regions do overlap...</p>
  
  <p>My attempt at this is thus far:</p>
  
  <pre><code>file1-read.table("file1.txt", sep='\t', header = F)
  file2=read.table("file2.txt", sep='\t', header = F)
  
  
  overlapping_regions&lt;-function(file1, file2){
    for(i in file1[,2]){
      x&lt;-seq(file1[i,2], file1[i,3])
      for(j in file1[,2]){
        y&lt;-seq(file2[j,2], file2[j,3])
        if(setequal(union(x, y), c(setdiff(x, y), intersect(x, y), setdiff(y, x)))){
          ####GET OVERLAP
        }
      }
    }
  }
  </code></pre>
  
  <p>The first problem with the above strategy is that I get the above error:</p>
  
  <pre><code> Error in seq.default(file1[i, 2], file1[i, 3]) : 
  </code></pre>
  
  <p>'from' cannot be NA, NaN or infinite</p>
  
  <p>Secondly I'm not sure if that strategy is right as I want every line of each file to be compared against the other to find <em>ANY</em> regions that are overlapping...</p>
  
  <p>So I am wondering if someone can help me with an R-script to parse these files such that I can make a new file that contains the overlapping regions between each start and end specifying columns and keep the features that pertain to each of the original files...</p>
  
  <p>So I would want my output to be something like this:</p>
  
  <pre><code>head(files_merged)
  
   chr   overlap   mappability       NRL    GC_content  more_features......
  chr1 start-end        1.0000       250
  chr1 start-end        0.5000       300
  chr1 start-end        0.0625       200
  </code></pre>
  
  <p>I ask this with the intention of trying to apply machine learning algorithms to try to predict genomic features.</p>
  
  <p>I can see (obviously) how my plan is flawed in that the regions specified in one file could be much smaller than those in another. Hence what I am also open to suggestions as to a better way to do this?</p>