Here is an example that takes a list of coordinates, then calculates the euclidean distance between each pair of points, then creates a path through the points of length steps
while never visiting the same point twice.
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)
