2016-12-01 41 views
0

在特定範圍我有兩個dataframes: 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 

與每個aprox的150000個條目。我想知道cnv_1的哪些片段與cnv_2以任何方式重疊,並且這對我來說是最重要的 - 以獲得重疊的特定區域。 舉例來說,這樣做的例子的data.frames,獲得:

chr  start end 
19 43403531 43519442 

非常感謝你

+0

看看這裏:https://stackoverflow.com/questions/3916195/finding-overlap-in-ranges-with-r – user1981275

+0

感謝@ user1981275,但我也需要知道重疊的確切範圍。我不知道IRanges –

回答

0

基於鏈接共享:

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 
+0

Hi @ joel.wilson,可能是也有可能獲得不重疊的行?指示NA例如...非常感謝。 –

+0

不適用於所有列? –

+0

對不起,但它不起作用,重疊的特定區域。 –

0

這裏有一個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表達式。

+0

是否可能感謝@Joe,但我想知道這兩個地區的共同點。兩個範圍具有共同的「開始」和「結束」。非常感謝 –

+0

查看編輯答案。 – Joe

+0

完美@Joe;並且知道不與cnv_2範圍重疊的cnv_1範圍(行),我的意思是說,在輸出中我獲得了與NA重疊的區域和區域。謝謝。 –