Skip to content

Instantly share code, notes, and snippets.

@JosiahParry
Created October 15, 2023 12:02
Show Gist options
  • Save JosiahParry/ad4eabf9b38e6c3c2402ca736a06527d to your computer and use it in GitHub Desktop.
Save JosiahParry/ad4eabf9b38e6c3c2402ca736a06527d to your computer and use it in GitHub Desktop.
Spatially implicit edges based on a minimum spanning tree
library(sfdep)
library(sfnetworks)
nb <- st_contiguity(guerry)
wt <- st_weights(nb)
listw <- recreate_listw(nb, wt)
mstree <- spdep::mstree(listw, 1)
edges <- data.frame(
from = as.integer(mstree[,1]),
to = as.integer(mstree[,2]),
weight = mstree[,3]
)
sfnetwork(
sf::st_centroid(guerry),
edges
)
@loreabad6
Copy link

To make the edges explicit:

library(sfdep)
library(sfnetworks)
library(tidygraph)
library(sf)

nb <- st_contiguity(guerry)
wt <- st_weights(nb)
listw <- recreate_listw(nb, wt)

mstree <- spdep::mstree(listw, 1)

edges <- data.frame(
  from = as.integer(mstree[,1]),
  to = as.integer(mstree[,2]),
  weight = mstree[,3]
)

sfn <- sfnetwork(
  sf::st_centroid(guerry),
  edges
)

edges_sflines <- sfn |> 
  activate(edges) |> 
  convert(to_spatial_explicit) |> 
  st_as_sf()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment