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

时间:2017-02-16 18:44:43

标签: r line distance

我查看了其他问题,例如thisthisthis,但所有这些都计算了到两个端点定义的线段的最短距离,而我没有能够做同样的但是对于由截距和斜率定义的线。

这是我的数据,我绘制并添加一条线,它的截距始终为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))))    

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

1 个答案:

答案 0 :(得分:1)

测试此(从here修改)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>

<table>
  <tr>
    <td style="background-color:#f00;">
      <select style="width:200px;">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
      </select>
    </td>
  </tr>
</table>

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

#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