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

Der*_*ran 4 r function vector distance angle

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

示例数据集

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))
Run Code Online (Sandbox Code Playgroud)

当前功能

现在,我已经成功地使用毕达哥拉斯开发了距离部分:

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

效果很好:

distance(from = From, to = To)


[1] 2.915476 1.414214 5.099020 1.414214
Run Code Online (Sandbox Code Playgroud)

但我不知道如何获得角度部分。

到目前为止我尝试过的:

我尝试调整这个问题的第二个解决方案

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)
Run Code Online (Sandbox Code Playgroud)

但我显然把事情搞砸了

所需输出

我希望将函数的角度部分添加到我的第一个函数中,在其中我可以获得起始数据帧和目标数据帧之间的距离和角度

Jam*_*mes 7

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

您使用的示例仅围绕一对点设计,t仅根据此原则使用转置。然而,它足够强大,可以在二维以上工作。

您的函数应该像距离函数一样进行矢量化,因为它需要许多点对(并且我们只考虑二维点)。

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
Run Code Online (Sandbox Code Playgroud)

sNaN是因为您的向量长度为​​零。


Ant*_*nis 5

怎么样:

library(useful)
df=To-From
cart2pol(df$x, df$y, degrees = F)
Run Code Online (Sandbox Code Playgroud)

返回:

# 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
Run Code Online (Sandbox Code Playgroud)

其中 r 是距离,theta 是角度