【问题标题】:Which R function can I use to find intersection points of two lines?我可以使用哪个 R 函数来查找两条线的交点?
【发布时间】:2020-10-23 08:06:56
【问题描述】:

我刚刚查看了关于 stackoverflow 的所有“在 R 中寻找交点”问题,它们要么是关于曲线和分布 like this one,要么使用 approxfun() 返回一个点列表,这些点对给定的数据点 like this one 进行线性插值。

那么,我可以使用哪个 R 函数来查找两条线的交点?

【问题讨论】:

标签: r


【解决方案1】:

如果你的线是由截距和斜率而不是两个点定义的,试试这个来找到交点:

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)

【讨论】:

    【解决方案2】:

    您可以使用PlaneGeometry 包:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      相关资源
      最近更新 更多