Find pairwise overlaps of intervals (segments)
Asked Answered
B

2

6

We are given two sets of intervals A and B. By an interval, I mean an ordered pair of integers such as c(2,5). I want to find all pairs of intervals - one from A and one from B - that have overlap.

For instance if A and B are as follows:

A=c(c(1,7), c(2,5), c(4, 16))
B=c(c(2,3), c(2,20))

Then FindOverlap(A, B) should return a matrix like below (the only zero element is because the 3rd interval of A does not overlap with the first interval of B):

1 1
1 1
0 1

Do you have any efficient idea?

Behemoth answered 15/8, 2013 at 7:55 Comment(0)
I
6

The intervals package seems to provide a solution here:

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

Ilocano answered 15/8, 2013 at 8:16 Comment(0)
S
1

Here's a little function I wrote to do the same thing. It could be improved substantially. Interesting problem though.

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
Suzannsuzanna answered 15/8, 2013 at 8:57 Comment(1)
Thanks for your answer. It is an interesting idea using only basic R capabilities, although the time complexity is O(n * m * p) which n is the number of items in A, m is the number of items in B, and p is the maximum length of an interval.Behemoth

© 2022 - 2024 — McMap. All rights reserved.