0

I have two bedfiles as dataframes in R, for which I want to map all overlapping regions to each other (similar to what bedtools closest would be able to do).

BedA:

chr   start   end
 2       100     500
 2       200     250
 3       275     300

BedB:

chr    start    end
  2       210      265
  2       99       106
  8       275      290

BedOut:

chr   start.A   end.A  start.B  end.B
 2       100     500      210      265
 2       100     500      99       106
 2       200     250      210      265

Now, I found this very similar question, which suggest to use iRanges. Using the proposed way seems works, but I have no idea how to turn the output into a data frame like "BedOut".

kEks
  • 304
  • 1
  • 9

2 Answers2

0

Here is a solution using the data.table package.

library(data.table)

chr = c(2,2,3)
start.A = c(100, 200, 275)
end.A = c(500, 250, 300)
df_A = data.table(chr, start.A, end.A)

chr = c(2,2,8)
start.B = c(210, 99, 275)
end.B = c(265, 106, 290)
df_B = data.table(chr, start.B, end.B)

First, inner join the data-tables on the key chr:

df_out = df_B[df_A, on="chr", nomatch=0]

Then filter the overlapping interval:

df_out = df_out[(start.A>=start.B & start.A<=end.B) | (start.B>=start.A & start.B<=end.A)]
setcolorder(df_out, c("chr", "start.A", "end.A", "start.B", "end.B"))

   chr start.A end.A start.B end.B
1:   2     100   500     210   265
2:   2     100   500      99   106
3:   2     200   250     210   265
otwtm
  • 1,779
  • 1
  • 16
  • 27
  • especially one bed file is quite large (420000 and 22000 rows). And combing both files beforehand exceeds my memory (similarity to the the inner_join function of dplyr). – kEks May 11 '20 at 15:09
0

Another data.table option using foverlaps:

setkeyv(BedA, names(BedA))
setkeyv(BedB, names(BedB))
ans <- foverlaps(BedB, BedA, nomatch=0L)
setnames(ans, c("start","end","i.start","i.end"), c("start.A","end.A","start.B","end.B"))

output:

   chr start.A end.A start.B end.B
1:   2     100   500      99   106
2:   2     100   500     210   265
3:   2     200   250     210   265

data:

library(data.table)
BedA <- fread("chr   start   end
2       100     500
2       200     250
3       275     300")

BedB <- fread("chr    start    end
2       210      265
2       99       106
8       275      290")
chinsoon12
  • 25,005
  • 4
  • 25
  • 35