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

创建R函数以查找两点之间的距离和角度,r,function,vector,distance,angle,R,Function,Vector,Distance,Angle,我试图创建或找到一个函数来计算两点之间的距离和角度,其思想是我可以有两个数据帧,x,y坐标如下: 示例数据集 但我不知道如何得到角度部分 到目前为止,我尝试的是: 我试着调整第二种解决方案 角度怎么样: library(useful) df=To-From cart2pol(df$x, df$y, degrees = F) 返回: # A tibble: 4 x 4 r theta x y <dbl> <dbl> <dbl>

我试图创建或找到一个函数来计算两点之间的距离和角度,其思想是我可以有两个数据帧,x,y坐标如下:

示例数据集 但我不知道如何得到角度部分

到目前为止,我尝试的是: 我试着调整第二种解决方案

角度怎么样:

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
#一个tible:4 x 4
rθx y
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是距离,θ是两个点之间的角度,我假设你是指两个向量之间的角度 由端点定义(假设起点是原点)

您使用的示例仅围绕一对点设计,而
t
transpose仅根据此原则使用。然而,它足够健壮,可以在两个以上的维度上工作

你的函数应该像距离函数一样矢量化,因为它需要很多对点(我们只考虑二维点)


距离函数的角度次要注释:不需要
abs
。正方形始终为正。+1表示距离()的自参考。
。。。也许您想使用
行和(从*到)
扩展
dot.prods
,以在多个维度中工作well@Tom不错,不过距离函数也需要修改才能适用于多个维度。似乎我没有太注意。这并不能回答这个问题。若要评论或要求作者澄清,请在其帖子下方留下评论。-但它返回重新设定的距离和角度。实际上,我的代码中的距离(返回TIBLE时的r变量)与上面显示的距离函数相同
distance(from = From, to = To)


[1] 2.915476 1.414214 5.099020 1.414214
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)
# 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
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