以整数间隔查找对应的数字

时间:2014-03-06 07:14:04

标签: r

我想获得两个整数间隔之间的对应数字。我的意见是:

    start1  end1    start2  end2    
      20     30      25      35
      25     35      20      30    
     100     190    126      226      
     126     226    100      190     

在第一行和第二行中,从第一(1)个间隔(2个第一个列)到第二个(2个)间隔(2个最后一个列)的重叠等于6个通信号码(25,26,27,28,29)和30)。

我的预期输出是这样的:

start1  end1    start2  end2    bp_overlapped   
   20    30       25      35          6        
   25    35       20      30          6
  100    190     126     226          65
  126    226     100     190          65

这是R中的矩阵。

谢谢。

2 个答案:

答案 0 :(得分:1)

您要搜索的功能是相交的。如果X是您的第一个矩阵,则可以执行此操作:

f <- function(x)
    length( intersect(seq(x[1],x[2],1), seq(x[3],x[4],1)) )
a <- apply(X,1,f)
X <- cbind(X,a)

函数apply对矩阵的每一行(如果第二个参数为1)或每列(如果第二个参数为2)应用函数。

答案 1 :(得分:1)

这是一个在速度方面难以击败的矢量化解决方案。如果你有很多片段(正如你经常在生物学中所做的那样,我猜你从术语bp_overlapped开始做),这会产生很大的不同。

pmax(
    0,                  # Returns 0 if the segments do not overlap at all
    1 + pmin(
        end1 - start1,  # Returns the length of seg 1 in case it is inside seg 2
        end2 - start2,  # Returns the length of seg 2 in case it is inside seg 1
        end1 - start2,  # Returns the overlap in case seg 1 is left of seg 2
        end2 - start1   # Returns the overlap in case seg 2 is left of seg 1
    )
)