I'm working with some spatial data and I want to turn the output of the st_nn
command (outputs a list) into a data frame that I can join. For example
library(nngeo)
library(tidyverse)
cities <- cities
towns <- towns
nearest <- st_nn(towns, cities, returnDist = TRUE, k = 2)
The output of the list give me the unique ID of the two nearest cities and also the distances for those cities. I would like this as a tibble with the following columns: 1) nearest_id
, (2) nearest_distance
, (3)second_nearest_id
, (4) second_nearest_distance
.
Here is what I tired
tibble(col1 = unlist(nearest[[1]]), col2 = unlist(nearest[[2]])) %>%
rowid_to_column(., "row_id") # for joining later on
I need to find a way to keep the id/distances for the two nearest neighbors separate and give the id/distances each its own column. I tried a st_join
with st_nn
but that doesn't return distance.