Skip to content

Instantly share code, notes, and snippets.

@brfitzpatrick
Created December 20, 2018 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brfitzpatrick/f88c5c3ac63df42375e5af6bd1ddaeb7 to your computer and use it in GitHub Desktop.
Save brfitzpatrick/f88c5c3ac63df42375e5af6bd1ddaeb7 to your computer and use it in GitHub Desktop.
Visualising Neighbourhood Weights
library(sp)
library(spdep)
library(tidyverse)
library(sf)
data(meuse)
nb.boundary.radius <- 750
nb.obj <- dnearneigh(x = select(meuse, x, y) %>% as.matrix(), d1 = 0, d2 = nb.boundary.radius, row.names = NULL, longlat = NULL, bounds=c("GT", "LE"))
nb.lstw <- nb2listw(neighbours = nb.obj, zero.policy = TRUE)
nb.dsts <- nbdists(nb = nb.obj, coords = select(meuse, x, y) %>% as.matrix())
# borrowed directly from the `spdep` docs:
inv.dst.weights <- lapply(nb.dsts, function(x) 1/(x/1e3))
inv.dst.lstw <- nb2listw(neighbours = nb.obj, glist = inv.dst.weights, style = 'B', zero.policy = TRUE)
ID.nb.spldf <- listw2lines(listw = inv.dst.lstw, coords = select(meuse, x, y) %>% as.matrix())
ID.nb.sf <- st_as_sf(x = ID.nb.spldf)
ggplot() +
geom_sf(data = ID.nb.sf %>% arrange(wt), aes(col = wt)) +
scale_colour_continuous(type = 'viridis', direction = -1) +
theme_bw() +
labs(colour = 'weight')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment