使用R,如何计算一个点到一条线的距离? [英] Using R, how to calculate the distance from one point to a line?

查看:412
本文介绍了使用R,如何计算一个点到一条线的距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有三个点,a,b,c. b和c链接成一条线.如何使用R计算从a到这条线的距离?有功能吗? 非常感谢

Suppose we have three points, a, b, c. b and c are linked to become a line. how to use R to calculate the distance from a to this line? 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.

二维案例

如果问题是二维的,则可以通过代表点xy坐标的数字对来定义点abc的位置. 以下函数可用于计算点a与距点bc定义的线的距离d:

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. 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 :

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手机壳

在三个维度上,问题稍微复杂一些.我们可以使用以下两个功能:

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

可以使用与上一个示例相同的方式在两个维度上调用计算距离的主要函数,唯一的区别是,现在这些点由表示xy,如下例所示:

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:

## 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, e.g., here and here.

这篇关于使用R,如何计算一个点到一条线的距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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