簡體   English   中英

我可以使用哪個 R function 找到兩條線的交點?

[英]Which R function can I use to find intersection points of two lines?

我剛剛查看了有關 stackoverflow 的所有“在 R 中查找交點”問題,它們要么是關於曲線和分布,要么是使用approxfun()返回一個點列表,這些點對給定的數據點進行線性插值。

那么,我可以使用哪個 R function 來找到兩條線的交點?

如果你的線是由截距和斜率而不是兩個點定義的,試試這個來找到交點:

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)

數字

您可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM