listw: Create Spatial Weights List

View source: R/hello.R

listwR Documentation

Create Spatial Weights List

Description

This function creates a spatial weights list using a shapefile and a dataset.

Usage

listw(
  shapefile_path,
  data,
  loc_shape,
  loc_data,
  weight_function = function(d) exp(-d/0.2)
)

Arguments

shapefile_path

A string specifying the file path to the shapefile.

data

A dataframe containing the variables to be analyzed.

loc_shape

A string specifying the column name in the shapefile used for merging.

loc_data

A string specifying the column name in the dataset that corresponds to the location variable.

weight_function

A function to calculate weights from distances. Defaults to 'function(d) exp(-d / 0.2)'.

Value

A spatial weights list object of class 'listw'.

Examples

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)
}

DHSr documentation built on April 4, 2025, 12:18 a.m.