Created
November 5, 2023 16:57
-
-
Save JosiahParry/eb7878fc375fb931ddd6675a2c591a2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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