-1

Sample code:

m=matrix(1:54,nrow=9)
l=1:6
plot(l,m[1,],type="l",xlim=1:6)
lines(l,m[2,])
lines(l,m[3,])
legend(2,3,legend=c("m1","m2","m3")))

Now, how can I find the point where say m1and m2 intersects? Any help is appreciated.

  • 1
    Relevant, possible dupes: https://stackoverflow.com/questions/62701178/which-r-function-can-i-use-to-find-intersection-points-of-two-lines; https://stackoverflow.com/questions/59189798/is-there-an-r-function-to-find-the-intersection-of-two-lines (interesting sf-based solution there); https://stackoverflow.com/questions/66176084/finding-the-intersect-of-two-lines-in-r; https://stackoverflow.com/questions/49521261/r-finding-the-intersect-of-two-lines?rq=1. – zephryl Apr 03 '23 at 19:21
  • The lines are parallel so they do not intersect. m[2, ] equals m[1, ] + 1. – G. Grothendieck Apr 04 '23 at 13:01

1 Answers1

1

Note, this is an answer to OP’s original question; they have since substantially edited their question.

This is an extension of @dcarlson's solution here, adding lm() to find intercepts and slopes from vectors of points.

intersection <- function(x, y1, y2) {
  l1 <- unname(coef(lm(y1 ~ x)))
  l2 <- unname(coef(lm(y2 ~ x)))
  x_int <- (l2[1] - l1[1]) / (l1[2] - l2[2])
  y_int <- l1[1] + l1[2] * x_int
  c(x = x_int, y = y_int)
}

# intersection of m2 and m5
m2_m5 <- intersection(l, m[2, ], m[5, ])
m2_m5
#        x         y 
# 0.720027 56.960115 

# intersection of m3 and m5
m3_m5 <- intersection(l, m[3, ], m[5, ])
m3_m5
#         x         y 
# -25.59092 -21.97391

The intersection of m3 and m5 is off your plot area, but we can plot the intersection of m2 and m5:

plot(l, m[2, ], type = "l", lwd = 2, col = 2, ylim = c(50, 90))
lines(l, m[3, ], type = "l", lwd = 2, col = 3)
lines(l, m[5, ], type = "l", lwd = 2, col = 5)
legend("topleft", legend = c("m2", "m3", "m5"), col = c(2, 3, 5), lty = 1, lwd = 2)
points(m2_m5[[1]], m2_m5[[2]], cex = 2, col = 2, lwd = 2)

zephryl
  • 14,633
  • 3
  • 11
  • 30