找出区间(片段)之间的成对重叠

6
我们有两组区间A和B。所谓的区间是指一对整数,例如c(2,5)。我想找到所有有重叠的区间对——一个来自A,一个来自B。
例如,如果A和B如下所示:
A=c(c(1,7), c(2,5), c(4, 16))
B=c(c(2,3), c(2,20))

如果执行FindOverlap(A, B),则应返回如下矩阵(唯一的零元素是因为A的第3个区间与B的第一个区间不重叠):

1 1
1 1
0 1

你有什么高效的想法吗?

2个回答

6

在这里,intervals包似乎提供了一个解决方案:

require("intervals")
A <- rbind(A1=c(1,7), A2=c(2,5), A3=c(4, 16))
B <- rbind(B1=c(2,3), B2=c(2,20))

# here you can also define if it is an closed or open interval
Aint <- Intervals(A)
Bint <- Intervals(B)

# that should be what you are looking for    
interval_overlap(Aint, Bint)

A nice demonstration


1
这是我写的一个小函数,用于执行相同的操作。它可以被大幅度改进。不过这是个有趣的问题。
f <- function(A,B){
  tmpA <-  lapply( A , function(x) min(x):max(x) )
  tmpB <-  lapply( B , function(x) min(x):max(x) )
  ids <- expand.grid( seq_along( tmpA ) , seq_along( tmpB ) )
  res <- mapply( function(i,j) any( tmpA[[i]] %in% tmpB[[j]] ) , i = ids[,1] , j = ids[ ,2] )
  out <- matrix( res , nrow = length( tmpA ) )
  return( out * 1 )
  }

 f(A,B)
     [,1] [,2]
[1,]    1    1
[2,]    1    1
[3,]    0    1

感谢您的回答。这是一个有趣的想法,只使用基本的R功能,尽管时间复杂度为O(n * m * p),其中n是A中项目的数量,m是B中项目的数量,p是间隔的最大长度。 - Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接