I have two linear fits that I've gotten from lm calls in my R script. For instance...
fit1 <- lm(y1 ~ x1)
fit2 <- lm(y2 ~ x2)
I'd like to find the (x,y) point at which these two lines (fit1
and fit2
) intersect, if they intersect at all.
I have two linear fits that I've gotten from lm calls in my R script. For instance...
fit1 <- lm(y1 ~ x1)
fit2 <- lm(y2 ~ x2)
I'd like to find the (x,y) point at which these two lines (fit1
and fit2
) intersect, if they intersect at all.
If the regression coefficients in the two models are not equal (which is almost certain) then the lines would intersect. The
coef
function is used to extract them. The rest is high school geometry.For Brandon: M^-1 %*% intercepts -->
Here's some high school geometry then ;-)
Or, to simplify the
solve
-based solution by @Dwin:I am a little surprised there isn't a built in function for this.
Here is a rudimentary function (for lm results), using the same general method as Tommy above. This uses the simple substitution method for two lines in the form "y=mx+b" to find the common intersection at y (y1=y2 ; m1*x + b1 = m2*x + b2) and solves for x:
Function definition
Test:
One way to avoid the geometry is to re-parameterize the equations as:
in terms of their intersection point
(x0, y0)
and then perform the fit of both at once usingnls
so that the returned values ofx0
andy0
give the result:EDIT: Note that the lines
xx<-...
andyy<-...
are new and thenls
line has been specified in terms of those and corrected.