【问题标题】:Creating R function to find both distance and angle between two points创建R函数来查找两点之间的距离和角度
【发布时间】:2018-07-04 18:27:03
【问题描述】:

我正在尝试创建或找到一个计算两点之间距离和角度的函数,我的想法是我可以有两个 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 数据帧之间的距离和角度

【问题讨论】:

  • 对您的距离函数的小评论:abs 是不必要的。正方形总是正数。

标签: r function vector distance angle


【解决方案1】:

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

您使用的示例仅围绕一对点设计,transpose 仅​​用于此原则。然而,它足够强大,可以在超过 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

NaNs 是由于您的向量长度为​​零。

【讨论】:

  • +1 用于对distance() 的自我引用...也许您想使用rowSums(from * to) 扩展您的dot.prods 以在多个维度上工作
  • @Tom 好点,虽然距离函数也需要修改以适用于多个维度。
  • 真的。看来我没太注意。
【解决方案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是距离,θ是角度

【讨论】:

  • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
  • 但它会返回重新计算的距离和角度。实际上,我的代码中的距离(返回 tibble 中的 r 变量)与上面显示的距离函数相同
猜你喜欢
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多