计算包含 xy 坐标列表的数据框中所有点之间距离的方法

Method for calculating distance between all points in a dataframe containing a list of xy coordinates

我确定之前已经有人回答过这个问题,但我一直找不到主题!

我正在尝试使用 r 生成数据框中 xy 坐标对之间所有距离的列表。数据存储如下:

ID = c('1','2','3','4','5','6','7')
x = c(1,2,4,5,1,3,1)
y = c(3,5,6,3,1,5,1)
df= data.frame(ID,x,y)

目前我可以使用以下方法计算两点之间的距离:

length = sqrt((x1 - x2)^2+(y1 - y2)^2).

但是,我不确定下一步该去哪里。我应该使用 plyr 中的东西还是 for 循环?

感谢您的帮助!

您可以使用自连接获取所有组合,然后应用您的距离公式。使用 tidyverse(来自 Hadley Wickham 的软件包组合)可以轻松实现所有这些:

# Load the tidyverse
library(tidyverse)

# Set up a fake key to join on (just a constant)
df <- df %>% mutate(k = 1) 

# Perform the join, remove the key, then create the distance
df %>% 
 full_join(df, by = "k") %>% 
 mutate(dist = sqrt((x.x - x.y)^2 + (y.x - y.y)^2)) %>%
 select(-k)

N.B。使用此方法,您还将计算每个点与其自身(以及所有其他点)之间的距离。不过,很容易过滤掉这些要点:

df %>% 
 full_join(df, by = "k") %>% 
 filter(ID.x != ID.y) %>%
 mutate(dist = sqrt((x.x - x.y)^2 + (y.x - y.y)^2)) %>%
 select(-k)

有关使用 tidyverse 软件包集的更多信息,我推荐 R for Data Science or the tidyverse website

你试过?dist吗,你列出的公式是欧式距离

dist(df[,-1])