if (requireNamespace("spData", quietly = TRUE)) {
library(dplyr)
library(sf)
# Load US states data
us_states <- spData::us_states
# Simplify for demonstration: Select a subset of columns
us_states_data <- us_states %>%
select(GEOID, NAME) %>%
mutate(mean_wealth = rnorm(nrow(us_states), 50, 10)) # Add mock data
# Define a temporary shapefile path
shapefile_path <- tempfile(fileext = ".shp")
sf::st_write(us_states, shapefile_path, quiet = TRUE)
# Use the listw function from the package
us_states_listw <- DHSr::listw(
shapefile_path = shapefile_path,
data = us_states_data %>% sf::st_drop_geometry(), # Drop geometry for compatibility
loc_shape = "GEOID",
loc_data = "GEOID",
weight_function = function(d) exp(-d / 0.2)
)
# Verify the spatial weights list
print(us_states_listw)
}
Run the code above in your browser using DataLab