Skip to content

Intersection of two sets of intervals

1 message · William Dunlap

#
The pmin/pmax approach fails if an open interval in
the first list intersects with more than one open
interval in the second.  You can deal with that by
a sorting trick that gives you the number of intervals
each time point is in and then selecting the time points
when the number of intervals covering it rises to 2 and
falls below 2.  This version ignores the possibility
that intervals in one list might overlap each other.
function(list1, list2)
{
        n1 <- nrow(list1)
        n2 <- nrow(list2)
        times <- c(list1$open, list2$open, list1$close, list2$close)
        o <- order(times)
        times <- times[o]
        nOpen <- cumsum(rep(c(1, 1, -1, -1), c(n1, n2, n1, n2))[o])
        bothOpen <- nOpen == 2
        # ==1 for eitherOpen
        change <- diff(c(FALSE, bothOpen))
        data.frame(open = times[change == 1], close = times[change ==
-1])
}
open close
1    1     4
2    5    10
open close
1  1.5   2.5
2  3.0  10.0
open close
1  1.5   2.5
2  3.0   4.0
3  5.0  10.0

Bill Dunlap
TIBCO Software Inc - Spotfire Division
wdunlap tibco.com 

-------------------------------------------------------------------
[R] Intersection of two sets of intervals

Thomas Meyer tm35 at cornell.edu 
Wed Apr 15 16:52:48 CEST 2009
Previous message: [R] Intersection of two sets of intervals
Next message: [R] Intersection of two sets of intervals
Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
pmax/pmin did the trick nicely -- the right-size tool I was hoping for.

Thanks to all,

-tom
On 4/15/2009 9:14 AM, ONKELINX, Thierry wrote:
------------------------------------------------------------------------
more
to
not
r-project.org]
is
to
data.frame:
can