[英]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循环中的东西吗?
谢谢你的帮助!
你试过吗?dist,你列出的公式是欧几里德距离
dist(df[,-1])
您可以使用自联接来获取所有组合,然后应用距离公式。 所有这一切都很容易使用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)
NB使用此方法,您还将计算每个点与其自身(以及所有其他点)之间的距离。 虽然过滤这些点很容易:
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或tidyverse
网站 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.