计算由R中的截距和斜率定义的从点到线的最短距离



我查看了这样的其他问题,但是所有这些都计算出由两个端点定义的线段的最短距离,而我无法执行相同的操作但是,对于由截距和斜率定义的线。

这是我的数据,我绘制并添加了一条线,该行将始终具有由两个变量的均值定义的0和斜率。

df <- data.frame(x = seq(1, 10, 1),
                 y = seq(1, 10, 2),
                 id = head(letters, 10))
plot(df$x, df$y, 
     abline(a = 0, b = (mean(df$x) / mean(df$y))))    

我正在尝试计算从每个点到线的最短距离。

测试此(从此处修改)

#Perpendicular distance from point 'a' to a line with 'slope' and 'intercept'
dist_point_line <- function(a, slope, intercept) {
    b = c(1, intercept+slope)
    c = c(-intercept/slope,0)       
    v1 <- b - c
    v2 <- a - b
    m <- cbind(v1,v2)
    return(abs(det(m))/sqrt(sum(v1*v1)))
}
dist_point_line(c(2,1), 1, 0)
#[1] 0.7071068

在您的情况下,您可以做这样的事情

apply(df, 1, function(x) dist_point_line(as.numeric(x[1:2]), slope = 1, intercept = 0) )
 #[1] 0.0000000 0.7071068 1.4142136 2.1213203 2.8284271 3.5355339 2.8284271 2.1213203 1.4142136 0.7071068

最新更新