0

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 graphenter image description here 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)

Phil
  • 7,287
  • 3
  • 36
  • 66
jennmaurice
  • 77
  • 1
  • 1
  • 8
  • 2
    Check out the options at this question https://stackoverflow.com/questions/49521261/r-finding-the-intersect-of-two-lines?rq=1 – AuthenticSporks Feb 12 '21 at 17:11
  • @AutenticSporks I was struggling to work out how to apply it to my code but I will re go over it – jennmaurice Feb 12 '21 at 17:12
  • Can you share some of your data using `dput(red)`? – LMc Feb 12 '21 at 17:31
  • structure(list(T = c(152L, 288L, 412L, 544L, 669L, 763L, 829L, 877L), O = c(0L, 0L, 8L, 11L, 13L, 16L, 18L, 19L), I = c(59L, 56L, 51L, 48L, 43L, 40L, 38L, 37L)), class = "data.frame", row.names = c(NA, -8L)) @LMc got it here – jennmaurice Feb 12 '21 at 17:41

2 Answers2

1

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.

SteveM
  • 2,226
  • 3
  • 12
  • 16
1

You can solve this system of equations as @SteveM said using some linear algebra, which is done below using the solve function.

  1. 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.
  2. You have coded the slope and intercept for your other line. The slope that you are plotting is 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.
  3. Using the form 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.
  4. The output of 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")

enter image description here

LMc
  • 12,577
  • 3
  • 31
  • 43