Skip to content

Instantly share code, notes, and snippets.

@JosiahParry
Created November 5, 2023 16:57
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 JosiahParry/eb7878fc375fb931ddd6675a2c591a2b to your computer and use it in GitHub Desktop.
Save JosiahParry/eb7878fc375fb931ddd6675a2c591a2b to your computer and use it in GitHub Desktop.
library(sf, quietly = TRUE)
library(spdep, quietly = TRUE)
nc <- read_sf(system.file("shape/nc.shp", package = "sf"))
# define neighbors
nb <- poly2nb(nc)
# choose variable
x <- nc$SID74
# create an isolated node
nb[[10]] <- 0L
# create a listw object
listw <- nb2listw(nb, zero.policy = TRUE)
# calculate lag with NA values
l1 <- lag.listw(listw, x)
# shortcut create KNN nbs
knn_nb <- sfdep::st_knn(nc$geometry, 3)
# second listw obj
listw_knn <- nb2listw(knn_nb)
# knn spatial lag
l2 <- lag.listw(listw_knn, x)
# impute values
imputed <- ifelse(is.na(l1), l2, l1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment