Reputation: 77
I have some code which plots two lines from a set of points. I need to find the intersect of the two.
red <- read.table("red.txt", header=TRUE) #Get's table
mag <- red$T #T values
outer <- red$O #outer values
inner <- red$I #inner values
plot(outer, mag) #plot outer points
abline(lm(mag~outer)) #line of best fit
abline(inner, mag) #add inner line
It produces a graph which is similar to what I want.
(I am aware it is not the most stylish). How can I find the coordinates of the lines crossing?
(sorry about the dodgy probably disgusting code I am just learning how to use it)
Upvotes: 0
Views: 2056
Reputation: 2301
Generate the equations of the lines from the slope/intercept (m/b) regression outputs. So
reg1 <- lm(y1 ~ x1)
reg2 <- lm(y2 ~ x2)
Provide the slopes (m1, m2) and the intercepts (b1, b2)
y1 = m1x1 + b1
y2 = m2x2 + b2
Since x1 = x2 = x and y1 = y2 = y then
m1x - y = -b1
m2x - y = -b2
You can solve the equations for the x,y unknowns.
Upvotes: 1
Reputation: 18612
You can solve this system of equations as @SteveM said using some linear algebra, which is done below using the solve
function.
lm
gives you the coefficients for the line of best fit you just have to store it, which is done below in the object fit
.mag[1]
and the intercept is inner[1]
. Note: you are passing abline
the vectors mag
and inner
, but this function takes single values so it is only using the first element of each vector.mx - y = -b
put the x
and negated y
coefficients into a matrix A
. These coefficients are m
and -1
for x
and y
. Put their negated intercepts into a vector b
.solve
will give you the x
and y
values (in that order) where the two lines intersect.fit <- lm(mag~outer)
plot(outer, mag) #plot outer points
abline(fit) #line of best fit
abline(inner[1], mag[1]) #add inner line
A <- matrix(c(coef(fit)[2], -1,
mag[1], -1), byrow = T, nrow = 2)
b <- c(-coef(fit)[1], -inner[1])
(coord <- solve(A, b))
[1] 1.185901 239.256914
points(coord[1], coord[2], col = "red")
Upvotes: 1