在同一数据框中找到下一个最近的点

时间:2020-10-07 04:37:15

标签: r coordinates spatial

我正在使用R-Studio,并且有一个数据框,其中有x,y的点。当我选择x0,y0时,我想找到下一个最近的点。然后,当我有x1,y1时,我想将它们用作x0,y0并找到下一个最近的点,即x2,y2。

该问题的答案有所帮助:Find the nearest X,Y coordinate using R 但是现在我需要第二部分的帮助来更新x0,y0。直到遍历我所有的数据为止。

2 个答案:

答案 0 :(得分:2)

这是一个解决方案,将您的问题作为旅行营业员问题解决...

样本数据

mydata <- data.frame( id = letters[1:4],
                      x = c(1,10,2,5),
                      y = c(1,10,4,6) )

#what does it look like?
library(ggplot2)
ggplot( mydata, aes( x = x, y = y, label = id)) + geom_point() + geom_text( vjust = -1 )

enter image description here

代码

#introducing the Travelling SalesPerson
#   install.packages("TSP")
library( TSP )

#calculate distances
d <- dist( mydata[-1] )
#create TSP model...
tsp <- TSP( d, labels = mydata$id )
#...and solve it. start on first point, using nearest neighbour
tsp_solved <- solve_TSP( tsp, method = "nn", start = 1 )
#so.. what do we travel like?
labels( tsp_solved )
#[1] "a" "c" "d" "b"

答案 1 :(得分:0)

这里是一个示例,它获取一个坐标列表,然后计算每对点之间的欧几里得距离,然后创建一条通过长度为steps的点的路径,而永远不会两次访问同一点。

library(tidyverse)

set.seed(1234)

distance_table <- tibble(id = 1:100, x = runif(0,100,n = 100), y = runif(0,100,n=100)) %>%
 (function(X)expand_grid(X, X %>% setNames(c("id_2", "x2","y2"))))  %>%
 filter(id != id_2) %>%
 mutate(euc_dist = sqrt((x - x2)^2 +(y-y2)^2))


steps = 25
starting_id = sample(1:100, 1)
results_holder = tibble(order = 1:steps, location_id = numeric(steps), x = numeric(steps), y = numeric(steps))
results_holder$location_id[1] <- starting_id
results_holder$x[1] <- unique(distance_table$x[distance_table$id == starting_id])
results_holder$y[1] <- unique(distance_table$y[distance_table$id == starting_id])

for(i in 2:steps){
 data_tmp <- distance_table %>% 
  filter(results_holder$location_id[i - 1] == id) %>% 
  filter(!(id_2 %in% results_holder$location_id)) %>%
  filter(euc_dist == min(euc_dist))
 results_holder$location_id[i] <- data_tmp$id_2[1]
 results_holder$x[i] <- data_tmp$x2[1]
 results_holder$y[i] <- data_tmp$y2[1]
}

results_holder

ggplot(distance_table %>% filter(!(id %in% results_holder$location_id)), aes(x, y)) +
 geom_point() + 
 geom_label(data = results_holder, aes(label = order), size = 2)

the plotted route