获取重叠的特定范围

Obtain the specific range that overlap

我有两个数据框: cnv_1

chr     start   end
3   62860387    63000898
12  31296219    31406907
14  39762575    39769146
19  43372386    43519442
19  56419263    56572829

cnv_2

chr     start   end
6   30994163    30995078
19  43403531    44608011
18  1731154 1833682
3   46985863    47164711

每个大约有 150000 个条目。我想知道 cnv_1 的哪些片段以任何方式与 cnv_2 重叠,并且 - 这对我来说是最重要的 - 以获得重叠的特定区域。 比如对例子的data.frames做,得到:

chr     start   end
19  43403531 43519442

非常感谢

这是一个 dplyr 链,它连接两个数据帧之间的公共区域,查找重叠并获取起始值和结束值。

library(dplyr)
inner_join(cnv_1, cnv_2, by="chr") %>% 
  filter(!(start.x > end.y | start.y > end.x)) %>%
  transmute(chr, start.o = ifelse(start.y > start.x, start.y, start.x),
                   end.o = ifelse(end.y > end.x, end.x, end.y))

输出为:

  chr  start.o    end.o
1  19 43403531 43519442

这对两个数据帧是对称的。如果您只想单向重叠,可以根据需要简化 filtertransmute 表达式。

基于link分享:

cnv_3 <- merge(cnv_1, cnv_2, by = "chr", suffixes = letters[1:2])
# below function has 3 conditions : 1 fully inside the interval and 2 partial overlap cases
func <- function(x){
  if(x["starta"]>x["startb"] & x["enda"]<x["endb"])
    x
  else if( x["starta"]<x["startb"] & x["enda"] < x["endb"]){
    x["starta"]=x["startb"]
    x
  } else if( x["starta"] >x["startb"]&x["starta"]<x["endb"]&x["enda"]>x["endb"]){
    x["enda"]=x["endb"]
    x
  }
  else
    c(x[1] ,rep(NA, length(x)-1))
}


df <-  data.frame(t(apply(cnv_3, 1, func)))
df <- df[!is.na(df[,1]),][1:3]
colnames(df) <- colnames(cnv_1)
# incase you want all the original cnv_1 rows with NA's for non-overlapping
xxx <- cnv_1[!(cnv_1$chr %in% df$chr),]
xxx$start <- xxx$end <- NA
rbind(xxx, df)
#   chr    start      end
#2   12       NA       NA
#3   14       NA       NA
#31   3       NA       NA
#4   19 43403531 43519442
#5   19       NA       NA