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

Creating R function to find both distance and angle between two points

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

示例数据集

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)

但我明明把事情搞砸了

期望的输出

我想将函数的角度部分添加到我的第一个函数中,在那里我得到起始和终止数据帧之间的距离和角度

怎么样:

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

哪个returns:

# 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 是距离,theta 是角度

两点之间的角度,我假设你指的是两个向量之间的角度 由端点定义(并假设开始是原点)。

您使用的示例仅围绕一对点设计,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

NaN是因为你有零长度向量。