[R] Intersection for two curves

Peter Ehlers ehlers at ucalgary.ca
Fri Apr 23 20:32:46 CEST 2010


On 2010-04-23 11:46, David Winsemius wrote:
>
> On Apr 23, 2010, at 1:06 PM, Muhammad Rahiz wrote:
>
>> Does anyone know of a method that I can get the intersection where the
>> red and blue curves meet i.e. the value on the x-axis?
>>
>> x <- 1:10
>> y <- 10:1
>> plot(x,y)
>> abline(lm(y~x),col="blue")
>> abline(h=2.5,col="red")
>
> Two ways :
>
>  > xy <- lm(y~x)
>  > xyf <- function(x) coef(xy)[1] +x*coef(xy)[2]
>
> # absolute difference
>  > optimise(f=function(x) abs(xyf(x)-2.5), c(1,10) )
> $minimum
> [1] 8.49998
>
> $objective
> (Intercept)
> 1.932015e-05
>
> #N minimize squared difference
>  > optimise(f=function(x) (xyf(x)-2.5)^2, c(1,10) )
> $minimum
> [1] 8.5
>
> $objective
> (Intercept)
> 3.155444e-30
>

Another (crude) way is to use locator(). I usually maximize
the plot window for this.

-- 
Peter Ehlers
University of Calgary



More information about the R-help mailing list