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

Calculating shortest distance from point to line defined by intercept and slope in R

我查看了其他问题,例如 this, this and this,但所有这些问题都计算了到由两个端点定义的线段的最短距离,而我无法做到这一点,但对于由截距和斜率。

这是我的数据,我绘制并添加了一条线,该线始终具有截距 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