创建R函数以查找两点之间的距离和角度

时间:2018-01-25 13:28:19

标签: r function vector distance angle

我正在尝试创建或找到一个计算两点之间的距离和角度的函数,我的想法是我可以有两个带有x,y坐标的data.frames,如下所示:

示例数据集

From <- data.frame(x = c(0.5,1, 4, 0), y = c(1.5,1, 1, 0))

To <- data.frame(x =c(3, 0, 5, 1), y =c(3, 0, 6, 1))

当前功能

目前,我已经设法使用毕达哥拉斯开发距离部分:

distance <- function(from, to){
  D <- sqrt((abs(from[,1]-to[,1])^2) + (abs(from[,2]-to[,2])^2))
  return(D)
}

哪种方法正常:

distance(from = From, to = To)


[1] 2.915476 1.414214 5.099020 1.414214

但我无法弄清楚如何获得角度部分。

到目前为止我尝试了什么:

我尝试调整this question

的第二个解决方案
angle <- function(x,y){
  dot.prod <- x%*%y 
  norm.x <- norm(x,type="2")
  norm.y <- norm(y,type="2")
  theta <- acos(dot.prod / (norm.x * norm.y))
  as.numeric(theta)
}

x <- as.matrix(c(From[,1],To[,1]))
y <- as.matrix(c(From[,2],To[,2]))
angle(t(x),y)

但我显然弄得一团糟

期望的输出

我想将函数的角度部分添加到我的第一个函数中,在这里我得到from和to dataframes之间的距离和角度

2 个答案:

答案 0 :(得分:4)

通过两点之间的角度,我假设你是两个向量之间的角度 由端点定义(假设起点是原点)。

您使用的示例仅围绕一对点设计,t ranspose仅用于此原则。然而,它足够强大,可以在2个以上的维度上工作。

你的函数应该像你的距离函数那样被矢量化,因为它期望有多对点(我们只考虑2维点)。

angle <- function(from,to){
    dot.prods <- from$x*to$x + from$y*to$y
    norms.x <- distance(from = `[<-`(from,,,0), to = from)
    norms.y <- distance(from = `[<-`(to,,,0), to = to)
    thetas <- acos(dot.prods / (norms.x * norms.y))
    as.numeric(thetas)
}

angle(from=From,to=To)
[1] 0.4636476       NaN 0.6310794       NaN

NaN是由于你有零长度向量。

答案 1 :(得分:2)

怎么样:

library(useful)
df=To-From
cart2pol(df$x, df$y, degrees = F)

返回:

# A tibble: 4 x 4
      r theta     x     y
  <dbl> <dbl> <dbl> <dbl>
1  2.92 0.540  2.50  1.50
2  1.41 3.93  -1.00 -1.00
3  5.10 1.37   1.00  5.00
4  1.41 0.785  1.00  1.00

其中r us是距离,θ是角度