R结合findOverlaps和countOverlaps的输出

R combine output of findOverlaps and countOverlaps

我有两组 IRanges 需要比较。我的目标是获得一个输出,如果存在重叠,则输出具有重叠位置,如果不重叠,则范围的偏移量列为负开始。至少,如果我无法获得偏移量,我希望得到一个“0”来表示没有重叠。例如:

xx<-IRanges(start=c(2,9,19,31,45), end=c(3,11,23,35,49))

        IRanges of length 5
     start end width
[1]      2   3     2
[2]      9  11     3
[3]     19  23     5
[4]     31  35     5
[5]     45  49     5

yy<-IRanges(start=c(4,10,19,33,45), end=c(5,13,25,38,48))

IRanges of length 5
     start end width
[1]      4   5     2
[2]     10  13     4
[3]     19  25     7
[4]     33  38     6
[5]     45  48     4

使用 findOverlaps + ranges 给我:

> fo <-findOverlaps(xx,yy)
> ranges(fo, xx, yy)
IRanges of length 4
    start end width
[1]    10  11     2
[2]    19  23     5
[3]    33  35     3
[4]    45  48     4

我希望最终输出是一个数据框或类似这样的东西:

       start end width
[1]     -1   0     0
[2]     10  11     2
[3]     19  23     5
[4]     33  35     3
[5]     45  48     4

我能够使用 countOverlaps 获取重叠范围的索引,使用 findOverlaps + 范围获取用于比较的命中对象,但我不知道如何组合结果以获得所需的输出。

library(IRanges)

f <- function(a,b)
{
  s <- max(a$start,b$start)  
  e <- min(a$end,b$end)

  if ( s <= e )
  {
    ovlp <- c( start = s,
               end   = e,
               width = e-s+1 )
  } else
  {
    ovlp <- c( start = e-s,
               end   = 0,
               width = NA )
  }

  return(ovlp)
}

findOvlp <- function( X, Y )
{
  if ( length(X) != length(Y) ){ stop("length(X) != length(Y)") }

  n <- length(X)

  X.df <- as.data.frame(X)
  Y.df <- as.data.frame(Y)

  Z <- data.frame( start = rep(NA,length(X)),
                   end   = rep(NA,length(X)),
                   width = rep(NA,length(X)) )

  for ( i in 1:n ) { Z[i,] <- f(X.df[i,],Y.df[i,]) }

  return( Z )
}

.

> xx<-IRanges(start=c(2,9,19,31,45), end=c(3,11,23,35,49))

> yy<-IRanges(start=c(4,10,19,33,45), end=c(5,13,25,38,48))

> findOvlp(xx,yy)
  start end width
1    -1   0    NA
2    10  11     2
3    19  23     5
4    33  35     3
5    45  48     4

我想你需要的是IRanges中的pintersect函数。

library(IRanges)
xx <- IRanges(start=c(2,9,19,31,45), end=c(3,11,23,35,49))
yy <- IRanges(start=c(4,10,19,33,45), end=c(5,13,25,38,48))

pintersect(xx, yy)
# IRanges of length 5
#     start end width
# [1]     4   3     0
# [2]    10  11     2
# [3]    19  23     5
# [4]    33  35     3
# [5]    45  48     4

width = 0 表示没有重叠。