计算由R中的截距和斜率定义的点到线的最短距离 [英] Calculating shortest distance from point to line defined by intercept and slope in R

查看:81
本文介绍了计算由R中的截距和斜率定义的点到线的最短距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了其他问题,例如,但是所有这些计算到由两个端点定义的线段的最短距离,而对于截距和坡度定义的线,我却无法做到这一点.

I looked at other questions like this, this and this, but all these calculate the shortest distance to a line segment defined by two endpoints, whereas I've not been able to do the same but for a line defined by an intercept and a slope.

这是我的数据,我绘制并添加了一条线,该线将始终具有0的截距和由两个变量的方式定义的斜率.

This is my data, which I plot and add a line that will always have an intercept of 0 and slope defined by the means of the two variables.

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))))    

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

I am trying to calculate the shortest distance from each point to the line.

推荐答案

对此进行测试(从此处修改)>

Test this (Modified from here)

#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

在您的情况下,您可以执行以下操作

In your case you could do something like this

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

这篇关于计算由R中的截距和斜率定义的点到线的最短距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆