【问题标题】:finding the next closest point in the same data frame在同一数据框中找到下一个最近点
【发布时间】:2020-10-07 04:37:15
【问题描述】:

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

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

【问题讨论】:

  • 如果最接近点m 是点n,然后最接近点nm,会发生什么?你看过dist吗?
  • 您可以运行命令dput(YOURDATA) 并将输出粘贴到您的问题中。如果您这样做,其他人将能够使用您的数据并提出更明智的问题来帮助您。

标签: r coordinates spatial


【解决方案1】:

这是一个解决方案,将您的问题作为旅行推销员问题来处理...

样本数据

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 )

代码

#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"

【讨论】:

    【解决方案2】:

    这是一个示例,它获取一个坐标列表,然后计算每对点之间的欧几里德距离,然后创建一条通过长度为 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)
    

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2019-10-24
      • 2021-09-21
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多