2

I just looked into all the "finding intersections in R" questions on stackoverflow and they are either about curves and distributions like this one or using approxfun() to return a list of points which linearly interpolate given data points like this one.

So,which R function can I use to find intersection points of two lines?

r2evans
  • 141,215
  • 6
  • 77
  • 149
Gillian
  • 45
  • 5

2 Answers2

4

If your lines are defined by intercept and slope rather than two points, try this to find the intersection:

intersect <- function(l1, l2){
    x <- (l2[1] - l1[1]) / (l1[2] - l2[2])
    y <- l1[1] + l1[2] * x
    return(xy=c(x, y))
}

# Lines defined by intercept and slope
l1 <- c(10, -2)     # Y = l1[1] + l1[2] * X
l2 <- c( 0, 2)      # Y = l2[1] + l2[2] * X
xy <- intersect(l1, l2)   # Returns the xy coordinates of the intersection
xy
# [1] 2.5 5.0
plot(xy[1], xy[2], xlim=c(0, 6), ylim=c(0, 10), cex=3)
abline(l1[1], l1[2])
abline(l2[1], l2[2])
abline(h=5, v=2.5, lty=3)
text(1, 8.5, "Line 1", srt=-45)
text(1, 2.5, "Line 2", srt=45)

Figure

dcarlson
  • 10,936
  • 2
  • 15
  • 18
2

You can use the PlaneGeometry package:

library(PlaneGeometry)

line1 <- Line$new(A = c(0,0), B = c(1,1))
line2 <- Line$new(A = c(0,2), B = c(4,2))
intersectionLineLine(line1, line2)
# [1] 2 2
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225