gw_do_local_lm: Undertakes a single weighted regression

View source: R/gw_regr_functions.R

gw_do_local_lmR Documentation

Undertakes a single weighted regression

Description

Returns the local GWR coefficients for a given bandwidth. This is usually run after the optimal bandwidth has been determined, within the gwregr function and not as a standalone function.

Usage

gw_do_local_lm(w, formula, data)

Arguments

w

A vector of weights with length equal to the number of observations in data.

formula

A formula to be used in the regression, with terms contained in the variables names of the input data.

data

A flat data table in data.frame, matrix or tibble format

Value

A vector of coefficient estimates in the order Intercept, Variable 1, Variable 2, etc

Examples

library(sf)
# load data and define a model formula
data(georgia)
formula = as.formula(MedInc ~ PctBach + PctEld)
##  1. how the function works
# define a distance matrix, a location and an adaptive bandwidth
dist_mat = as.matrix(dist(st_coordinates(st_centroid(georgia)), upper = T, diag = T))
obs_index = 70
bw = 30
# create the nearby function - see the help for `gw_get_nearby` in the gw package
nearby_func = gw_get_nearby(adaptive = TRUE)
# apply to get an index of locations and get a vector of distances
index = nearby_func(obs_index, dist_mat, bw)
dists = dist_mat[obs_index,index]
# create the weighting function and weight the nearby locations 
#  - see the help for `gw_get_weight` in the gw package
weight_func = gw_get_weight(kernel = "bisquare", adaptive = TRUE)
# apply the weight function to the distances and extend to a vector of length observations
w = weight_func(bw, dists)
w_vec = rep(0, nrow(georgia))
w_vec[index] = w
# extract the coefficients for this location
gw_do_local_lm(w_vec, formula, georgia)
## 2. Using the function operationally


gwverse/gwregr documentation built on May 12, 2022, 8:41 p.m.