[R] finding the intersection of two vectors

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Thu Jul 7 11:42:32 CEST 2011


On Wed, Jul 6, 2011 at 9:43 PM, Data Analytics Corp.
<walt at dataanalyticscorp.com> wrote:

> close enough.  I can't figure out how to find the price value at which the
> two curves intersect.  Going back to the economics interpretation, I want
> the price where supply equals demand.  Any suggestions as to how I can find
> that price point in R?  Any functions that help?

 You could roll out the 100,000-pound gorilla that is rgeos, treat the
two lines as spatial lines and then use gIntersection:

 > x1
 [1]  3  4  6  8 10
 > x2
 [1]  1  2  6  7 10
 > y1
 [1] 0.23898824 0.48215370 0.45215557 0.08049115 0.18068038
 > y2
 [1] 0.2749391 0.3638511 0.1650239 0.3064780 0.8515887
 > s1=SpatialLines(list(Lines(list(Line(cbind(x1,y1))),ID=1)))
 > s2=SpatialLines(list(Lines(list(Line(cbind(x2,y2))),ID=1)))
 > gIntersection(s1,s2)
 SpatialPoints:
          x         y
 1 3.256617 0.3013887
 1 6.877310 0.2891230
 Coordinate Reference System (CRS) arguments: NA

Here my example crosses twice at those x-y coordinates. Note that if
the two lines are exactly equal along a line, you'll get back a
SpatialLines object as part of your result. In your case this would be
if supply dropped to 24 as demand rose to 24 and they both stayed like
that for some time before crossing. If you want the first time that
the values are equal you'd just take the minimum X-coordinate in the
returned object...

 But yeah, it might be overkill, but possibly handy if you want to
compute multiple times when two curves cross.

Barry



More information about the R-help mailing list