[英]Using R, how to calculate the distance from one point to a line?
Suppose we have three points, a, b, c. 假设我们有三个点,a,b,c。 b and c are linked to become a line.
b和c链接成一条线。 how to use R to calculate the distance from a to this line?
如何用R来计算从a线到这条线的距离? Is there any function?
有什么功能吗? Thanks a lot
非常感谢
It has to be distinguished whether we are dealing with a two-dimensional or a three-dimensional case. 必须区分我们是处理二维还是三维情况。
2D case 2D案例
If the problem is two-dimensional, the position of the points a
, b
and c
can be defined by pairs of numbers which represent the points' x
and the y
coordinates. 如果问题是二维的,则点
a
, b
和c
可以由表示点的x
和y
坐标的数字对来定义。 The following function can be used to calculate the distance d
of the point a
from the line defined by the two points b
and c
: 以下函数可用于计算点
a
与由两点b
和c
定义的直线的距离d
:
dist2d <- function(a,b,c) {
v1 <- b - c
v2 <- a - b
m <- cbind(v1,v2)
d <- abs(det(m))/sqrt(sum(v1*v1))
}
Here is an example showing how the function can be applied: 这是一个示例,说明如何应用该功能:
## two-dimensional case:
a2 <- c(0,2)
b2 <- c(2,0)
c2 <- c(1,3)
d2 <- dist2d(a2,b2,c2) # distance of point a from line (b,c) in 2D
#> d2
#[1] 1.264911
3D case 3D案例
In three dimensions, the problem is slightly more complicated. 在三个方面,问题稍微复杂一些。 We can use the following two functions:
我们可以使用以下两个功能:
dist3d <- function(a,b,c) {
v1 <- b - c
v2 <- a - b
v3 <- cross3d_prod(v1,v2)
area <- sqrt(sum(v3*v3))/2
d <- 2*area/sqrt(sum(v1*v1))
}
cross3d_prod <- function(v1,v2){
v3 <- vector()
v3[1] <- v1[2]*v2[3]-v1[3]*v2[2]
v3[2] <- v1[3]*v2[1]-v1[1]*v2[3]
v3[3] <- v1[1]*v2[2]-v1[2]*v2[1]
return(v3)
}
The main function to calculate the distance can be called in the same way as in the previous example in two dimensions, with the sole difference that now the points are defined by three coordinates representing x
, y
and z
, as shown in the example below: 计算距离的主要功能可以在前面的例子中以二维方式调用,唯一的区别是现在这些点由表示
x
, y
和z
的三个坐标定义,如下例所示:
## three-dimensional case:
a3 <- c(0,0,2)
b3 <- c(1,0,0)
c3 <- c(2,3,1)
d3 <- dist3d(a3,b3,c3) # distance of point a from line (b,c) in 3D
#> d3
#[1] 2.215647
The equations used in this answer are described in various textbooks and can be found, eg, here and here . 本答案中使用的等式在各种教科书中描述,并且可以在例如此处和此处找到 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.