Message-ID: <49E5DCEA.3080309@stats.uwo.ca>
Date: 2009-04-15T13:11:06Z
From: Duncan Murdoch
Subject: Intersection of two sets of intervals
In-Reply-To: <49E5DA31.5000902@cornell.edu>
On 4/15/2009 8:59 AM, Thomas Meyer wrote:
> Hi,
>
> Algorithm question: I have two sets of "intervals", where an interval is
> an ordered pair [a,b] of two numbers. Is there an efficient way in R to
> generate the intersection of two lists of same?
>
> For concreteness: I'm representing a set of intervals with a data.frame:
>
> > list1 = as.data.frame(list(open=c(1,5), close=c(2,10)))
> > list1
> open close
> 1 1 2
> 2 5 10
>
> > list2 = as.data.frame(list(open=c(1.5,3), close=c(2.5,10)))
> > list2
> open close
> 1 1.5 2.5
> 2 3.0 10.0
>
> How do I get the intersection which would be something like:
> open close
> 1 1.5 2.0
> 2 5.0 10.0
>
> I wonder if there's some ready-built functionality that might help me
> out. I'm new to R and am still learning to vectorize my code and my
> thinking. Or maybe there's a package for interval arithmetic that I can
> just pull off the shelf.
pmax and pmin should be helpful. I don't know how you want to represent
empty intersections, but I'd just compute the pmax of the lower bounds,
the pmin of the upper bounds, and then if the new upper bound is less
than the new lower bound, treat it as empty.
Duncan Murdoch