library(ggplot2) # Graphics library
library(sf) # Spatial data types and handling
library(spdep) # Diagnosing spatial dependence
library(spatialreg) # Spatial lag and spatial error model
theme_set(theme_light())15. Spatial regression in R
In geography, many regression problems involve geographic locations. Using locational data can lead to spatial dependence (spatial autocorrelation) and spatial heterogeneity or trends (non-stationarity). This session focuses on spatial dependence, specifically:
- Diagnosing spatial dependence in regression models
- Spatial lag models
- Spatial error models
- Choosing and comparing spatial regression models
Packages
Sources of spatial dependence
Before testing for spatial dependence, we need to understand the two principal sources of spatial dependence. The first is an explicit interaction between spatial units: spatial diffusion happens when spatially proximate units are influenced directly by their neighbors, and vice versa. Spatial diffusion effects can be incorporated in spatial lag models by including a spatially lagged response variable as predictor. Second, neighboring units may be similar even if there is no direct exchange or interaction between them. They may be similar just because they share the same underlying process by being geographically clustered. Such spatial dependence may be called attributional dependence because it is related to neighboring locations sharing the same attributes. Sometimes we can account for these attributional sources by including them as explanatory variables in the model (e.g., soil properties, climate). If that doesn’t work, then the model will exhibit spatial dependence in the error terms. Spatial error dependence can be modeled via a spatially lagged error term (spatial error model).
Linear regression model
For this exercise, we use the meuse data from the session on spatial interpolation. As a starting point, we fit an ordinary linear regression model that explains log-transformed zinc concentration by elevation and square-root-transformed distance to the river. Linear regression assumes independent residuals. With spatial data, this assumption is often violated because nearby samples tend to have similar residuals. Our first question is therefore: are the residuals spatially independent?
meuse <- read_sf("data/meuse.gpkg")
zinc.lm <- lm(log(zinc) ~ elev + sqrt(dist), data = meuse)
summary(zinc.lm)
Call:
lm(formula = log(zinc) ~ elev + sqrt(dist), data = meuse)
Residuals:
Min 1Q Median 3Q Max
-0.99144 -0.22853 0.00209 0.22244 0.98324
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.64157 0.25206 34.284 < 2e-16 ***
elev -0.23217 0.03426 -6.777 2.54e-10 ***
sqrt(dist) -1.97766 0.16025 -12.341 < 2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.3827 on 152 degrees of freedom
Multiple R-squared: 0.7226, Adjusted R-squared: 0.7189
F-statistic: 198 on 2 and 152 DF, p-value: < 2.2e-16
Both predictors are significant, and the model explains about 72% of the variance in log(zinc). However, these p-values assume independent residuals. If the residuals are spatially autocorrelated, the standard errors are typically underestimated and the predictors appear more significant than they are.
A first visual check is to map the residuals. If they are spatially independent, positive (blue) and negative (red) residuals should be randomly scattered. Clusters of similar colors suggest spatial autocorrelation. Since meuse is an sf object, we can plot it with geom_sf() instead of geom_point().
meuse$residuals <- residuals(zinc.lm)
ggplot(meuse, aes(col = residuals)) +
geom_sf() +
scale_color_gradient2()
The residuals are not randomly scattered. Nearby samples often share the same sign: for example, there is a cluster of large positive residuals in the central part of the study area and several clusters of negative residuals in the southern part. This suggests spatial autocorrelation. Visual impressions can be misleading, however, so next we test this formally.
Spatial weights
To test for spatial autocorrelation, we first need to identify the neighbors of each sample. The function dnearneigh identifies neighbors of points by Euclidean distance between lower (greater than) and upper (less than or equal to) bounds. The distances are in meters because the meuse data use a projected coordinate reference system (check with st_crs(meuse)). See also knearneigh/knn2nb for k-nearest neighbors and poly2nb for polygon neighborhoods.
meuse.nb <- dnearneigh(meuse, d1 = 0, d2 = 200)The result is an nb object, which is a list of vectors. Each vector contains the numerical indices of the observations. For example, the first vector meuse.nb[[1]] contains the indices of the neighbors of the first observation. The first observation has 2 neighbors (observations 2, 3), and the second observation has 3 neighbors (observations 1, 3, 8).
str(meuse.nb, list.len=5, give.attr = FALSE) # show content of first 5 list entriesList of 155
$ : int [1:2] 2 3
$ : int [1:3] 1 3 8
$ : int [1:4] 1 2 4 7
$ : int [1:3] 3 5 7
$ : int [1:4] 4 6 7 10
[list output truncated]
Next, we need to assign weights to each neighbor with the nb2listw function. In our example, each neighboring sample (point/polygon) is assigned equal weight (style="W"). This is accomplished by assigning the fraction 1/(number of neighbors) to each neighboring sample.
meuse.lw <- nb2listw(meuse.nb, style = "W", zero.policy = TRUE)The result is a listw object that contains the neighbor indices (meuse.lw$neighbours) and the corresponding neighbor weights (meuse.lw$weights). With a distance of 200 m, 5 points have no neighbors (check with sum(card(meuse.nb) == 0)). The zero.policy = TRUE option allows for such observations without neighbors; with zero.policy = FALSE, nb2listw would return an error. Use this option with caution, since you may not be aware of observations without neighbors in your dataset.
str(meuse.lw$weights, list.len=5, give.attr = FALSE) List of 155
$ : num [1:2] 0.5 0.5
$ : num [1:3] 0.333 0.333 0.333
$ : num [1:4] 0.25 0.25 0.25 0.25
$ : num [1:3] 0.333 0.333 0.333
$ : num [1:4] 0.25 0.25 0.25 0.25
[list output truncated]
Moran’s I
Moran’s I is a common measure of spatial autocorrelation. It compares the value at each location with the values at its neighboring locations. Values of Moran’s I near zero indicate a random spatial pattern. Positive values indicate that neighbors tend to have similar values, and negative values indicate that neighbors tend to have dissimilar values.
Moran’s I is often applied to an observed variable, for example zinc concentration. Here, we apply it to the residuals of our regression model instead. The question is not whether zinc itself is spatially clustered, but whether the part of zinc that the model cannot explain is spatially clustered.
The Moran’s I test for regression residuals is implemented in the function lm.morantest. This function operates on an lm object and requires a listw spatial weights object. Since our listw object meuse.lw contains observations without neighbors, we also need to set zero.policy = TRUE.
lm.morantest(zinc.lm, meuse.lw, zero.policy = TRUE)
Global Moran I for regression residuals
data:
model: lm(formula = log(zinc) ~ elev + sqrt(dist), data = meuse)
weights: meuse.lw
Moran I statistic standard deviate = 6.7153, p-value = 9.385e-12
alternative hypothesis: greater
sample estimates:
Observed Moran I Expectation Variance
0.415342780 -0.013332733 0.004075003
The residuals of the linear regression model showed significant positive spatial autocorrelation within a distance of 200 m (Moran’s I = 0.42, z = 6.72, p < 0.001).
The standard moran.test assumes that, under the null hypothesis of no spatial autocorrelation, the values are independent. Regression residuals violate this assumption even when there is no spatial autocorrelation: fitting the model forces them to sum to zero and to be uncorrelated with the predictors. This changes the expected value and variance of Moran’s I under the null hypothesis. lm.morantest accounts for this, while moran.test does not. Below, we still use moran.plot and moran.test on the residuals to explore spatial patterns, but the formal test should use lm.morantest.
Understanding Moran’s I
To see what Moran’s I measures, we compute for each sample the mean residual of its neighbors. This is called the spatially lagged residual. We then plot the spatially lagged residuals against the residuals themselves.
resid.lag <- lag.listw(meuse.lw, meuse$residuals, zero.policy = TRUE)
plot(meuse$residuals, resid.lag)
The scatterplot shows a positive relationship: samples with negative residuals tend to have neighbors with negative residuals, and samples with positive residuals tend to have neighbors with positive residuals. The function moran.plot creates the same plot and adds a regression line.
moran.plot(meuse$residuals, meuse.lw, zero.policy = TRUE)
The slope of this regression line is Moran’s I. We can verify this by fitting the regression ourselves: the slope (0.415) equals the Moran’s I value from the test above.
lm(resid.lag ~ meuse$residuals)
Call:
lm(formula = resid.lag ~ meuse$residuals)
Coefficients:
(Intercept) meuse$residuals
0.008047 0.415343
Sensitivity analysis
So far, we defined neighbors as all samples within 200 m. This choice is somewhat arbitrary, and Moran’s I depends on it: spatial autocorrelation is scale-dependent. To see how sensitive our result is, we repeat the Moran’s I test for a range of neighborhood distances (the upper limit d2 in dnearneigh) from 50 m to 2000 m and plot Moran’s I against distance.
Note that this means running 40 tests on the same residuals. With so many tests, some will be significant by chance, and the tests are not independent because the neighborhoods overlap. The p-values are therefore not adjusted for multiple testing, and we use them only as an exploratory guide, not as formal tests for each distance.
# neighborhood distances (upper limit d2) to test, in meters
distances <- seq(50, 2000, by = 50)
# table to store the results for each distance
sens <- data.frame(distance = distances, moran_I = NA, p_value = NA)
for (i in seq_along(distances)) {
# neighbors and spatial weights for the current distance
nb <- dnearneigh(meuse, d1 = 0, d2 = distances[i])
lw <- nb2listw(nb, style = "W", zero.policy = TRUE)
# Moran I test of the regression residuals
test <- lm.morantest(zinc.lm, lw, zero.policy = TRUE)
# store Moran's I and p-value in row i
sens$moran_I[i] <- test$estimate["Observed Moran I"]
sens$p_value[i] <- test$p.value
}
ggplot(sens, aes(x = distance, y = moran_I)) +
geom_hline(yintercept = 0, linetype = "dashed") +
geom_line() +
geom_point(aes(col = p_value < 0.05)) +
labs(x = "Neighborhood distance (m)", y = "Moran's I of residuals",
col = "p < 0.05\n(unadjusted)")
Moran’s I is highest at a neighborhood distance of 200 m. With larger neighborhoods, more distant and less similar samples are included, so Moran’s I gradually decreases and is close to zero beyond roughly 800 m. At very short distances (50 m), almost all samples have no neighbors, so Moran’s I is not meaningful there. Overall, the residuals show the strongest spatial autocorrelation over a few hundred meters. Because the decrease is gradual and the p-values are unadjusted, we should not read a precise distance at which the autocorrelation ends from this plot.
Spatial lag model
The spatial lag model (also called spatial autoregressive lag model) represents spatial diffusion: the response at a location is directly influenced by the response at neighboring locations. It extends the linear model by adding the spatially lagged response \(WY\) as a predictor:
\[ Y = \rho W Y + X\beta + \epsilon \]
Here, \(W\) is the spatial weights matrix, so \(WY\) is the mean response of the neighbors, just like the spatially lagged residuals we computed above. The coefficient \(\rho\) is the spatial dependence parameter: it describes how strongly responses are associated across neighboring locations. The error term \(\epsilon \sim N(0, \sigma^2)\) is assumed to be independent.
The spatial lag model is fitted by Maximum Likelihood (ML) with the function lagsarlm() from the spatialreg package. It requires a model formula, a data set, and a listw spatial weights object.
# fit spatial lag model (using the 200 m spatial weights meuse.lw from above)
zinc.slm <- lagsarlm(log(zinc) ~ elev + sqrt(dist),
data = meuse,
listw = meuse.lw,
zero.policy = TRUE)
summary(zinc.slm)
Call:lagsarlm(formula = log(zinc) ~ elev + sqrt(dist), data = meuse,
listw = meuse.lw, zero.policy = TRUE)
Residuals:
Min 1Q Median 3Q Max
-0.9711349 -0.2303691 -0.0042542 0.2166367 0.9730583
Type: lag
Regions with no neighbours included:
30 106 108 148 155
Coefficients: (asymptotic standard errors)
Estimate Std. Error z value Pr(>|z|)
(Intercept) 8.311927 0.329561 25.2212 < 2.2e-16
elev -0.228186 0.033823 -6.7465 1.515e-11
sqrt(dist) -1.879407 0.168725 -11.1388 < 2.2e-16
Rho: 0.044484, LR test value: 2.4399, p-value: 0.11829
Asymptotic standard error: 0.028539
z-value: 1.5587, p-value: 0.11907
Wald statistic: 2.4295, p-value: 0.11907
Log likelihood: -68.32293 for lag model
ML residual variance (sigma squared): 0.1413, (sigma: 0.3759)
Number of observations: 155
Number of parameters estimated: 5
AIC: 146.65, (AIC for lm: 147.09)
LM test for residual autocorrelation
test value: 39.746, p-value: 2.893e-10
The spatial lag coefficient \(\rho\) (Rho) is small (0.04) and not significant, neither in the Likelihood Ratio (LR) test (p = 0.118) nor in the asymptotic z-test (p = 0.119). The LR test compares the models with and without the spatial lag term, so adding the spatially lagged response does not improve the model.
To account for the spatial autocorrelation in the residuals, we extended the linear regression model of log-transformed zinc concentration into a spatial lag model, using neighbors within 200 m. Zinc concentrations at neighboring locations did not explain additional variation (ρ = 0.04, LR = 2.44, p = 0.12), so the spatial lag model did not improve on the linear regression model.
Spatial error model
The spatial error model represents attributional dependence: neighboring locations are similar because they share unmeasured factors (e.g., soil properties or flooding history), not because they directly influence each other. Instead of adding a spatial term for the response, the model allows the regression errors to be spatially autocorrelated:
\[ Y = X\beta + u, \quad u = \lambda W u + \epsilon \]
Here, \(u\) is the spatially autocorrelated regression error, \(W\) is the spatial weights matrix, and \(\epsilon\) is the independent error term. The coefficient \(\lambda\) measures how strongly the error at a location depends on the errors of its neighbors.
The spatial error model is fitted with the function errorsarlm() from the spatialreg package, using the same arguments as lagsarlm().
zinc.sem <- errorsarlm(log(zinc) ~ elev + sqrt(dist),
data = meuse,
listw = meuse.lw,
zero.policy = TRUE)
summary(zinc.sem)
Call:errorsarlm(formula = log(zinc) ~ elev + sqrt(dist), data = meuse,
listw = meuse.lw, zero.policy = TRUE)
Residuals:
Min 1Q Median 3Q Max
-1.03979 -0.19864 0.02663 0.19649 0.85387
Type: error
Regions with no neighbours included:
30 106 108 148 155
Coefficients: (asymptotic standard errors)
Estimate Std. Error z value Pr(>|z|)
(Intercept) 8.757203 0.239257 36.6016 < 2.2e-16
elev -0.250525 0.031123 -8.0494 8.882e-16
sqrt(dist) -1.912453 0.193397 -9.8887 < 2.2e-16
Lambda: 0.51114, LR test value: 38.267, p-value: 6.1697e-10
Asymptotic standard error: 0.073506
z-value: 6.9537, p-value: 3.5594e-12
Wald statistic: 48.353, p-value: 3.5593e-12
Log likelihood: -50.40936 for error model
ML residual variance (sigma squared): 0.10296, (sigma: 0.32087)
Number of observations: 155
Number of parameters estimated: 5
AIC: 110.82, (AIC for lm: 147.09)
The spatial error coefficient \(\lambda\) (Lambda) is large (0.51) and significant (LR test, p < 0.001). Unlike the spatial lag model, the spatial error model clearly improves on the linear regression model. The coefficients of elevation and distance to the river change only slightly compared to the linear model.
A spatial error model of log-transformed zinc concentration, using neighbors within 200 m, captured the residual spatial autocorrelation in a spatially autocorrelated error term (λ = 0.51, LR = 38.27, p < 0.001) and improved on the linear regression model. Elevation and distance to the river remained significant predictors of zinc concentration.
Rao’s score test
We have now fitted both spatial models and found that the spatial error model fits better. In practice, however, we would like to know which model is more appropriate before fitting them. This is what Rao’s score tests (also called Lagrange Multiplier tests) do: they use only the residuals of the linear model to test whether adding a spatial term would improve it.
RSerrtests whether a spatially autocorrelated error term should be added (spatial error model).RSlagtests whether a spatially lagged response should be added (spatial lag model).
lm.RStests(zinc.lm, meuse.lw, test = c("RSerr", "RSlag"), zero.policy = TRUE)
Rao's score (a.k.a Lagrange multiplier) diagnostics for spatial dependence
data:
model: lm(formula = log(zinc) ~ elev + sqrt(dist), data = meuse)
test weights: meuse.lw
RSerr = 43.733, df = 1, p-value = 3.764e-11
Rao's score (a.k.a Lagrange multiplier) diagnostics for spatial dependence
data:
model: lm(formula = log(zinc) ~ elev + sqrt(dist), data = meuse)
test weights: meuse.lw
RSlag = 2.4563, df = 1, p-value = 0.1171
The test for the spatial error term is significant (p < 0.001), whereas the test for the spatial lag term is not (p = 0.117). This points to the spatial error model and agrees with the results of the fitted models above. In practice, these tests are therefore a useful first step for choosing a spatial model. If both tests are significant, the robust versions (test = c("adjRSerr", "adjRSlag")) help to decide which model is more appropriate.
Rao’s score tests on the residuals of the linear regression model indicated a spatially autocorrelated error term (RS = 43.73, p < 0.001) but no spatial lag effect (RS = 2.46, p = 0.12), supporting the use of a spatial error model.
Model comparison
Finally, we compare the three models: the linear model, the spatial lag model, and the spatial error model. We use two criteria: how well each model fits the data (AIC) and how much spatial autocorrelation remains in its residuals.
AIC
We cannot compare the models with \(R^2\), because the spatial models are fitted by Maximum Likelihood and have no standard \(R^2\). We also cannot use an LR (likelihood ratio) test to compare the two spatial models directly, because neither model is a special case of the other (they are not nested). Instead, we use the Akaike Information Criterion (AIC), where lower values indicate a better model.
AIC(zinc.lm, zinc.slm, zinc.sem) df AIC
zinc.lm 4 147.0857
zinc.slm 5 146.6459
zinc.sem 5 110.8187
The spatial lag model reduces the AIC only slightly compared to the linear model (146.6 vs. 147.1), whereas the spatial error model reduces it substantially (110.8). The spatial error model is therefore the best of the three models.
Remaining spatial autocorrelation
Next, we check how much spatial autocorrelation remains in the residuals of each model. As in the sensitivity analysis, we compute Moran’s I for a range of neighborhood distances, now for all three models. lm.morantest only works for linear models. For the spatial models, we therefore use moran.test, but only to compute Moran’s I, not to test its significance (see the note on lm.morantest above).
# the three models to compare
models <- list("Linear model" = zinc.lm,
"Spatial lag model" = zinc.slm,
"Spatial error model" = zinc.sem)
# neighborhood distances to test, in meters
distances <- seq(50, 2000, by = 50)
# empty table to collect the results
comp <- data.frame()
for (d in distances) {
# neighbors and spatial weights for the current distance
nb <- dnearneigh(meuse, d1 = 0, d2 = d)
lw <- nb2listw(nb, style = "W", zero.policy = TRUE)
for (m in names(models)) {
# Moran's I of the residuals of model m
test <- moran.test(residuals(models[[m]]), lw, zero.policy = TRUE)
# add one row to the results table
comp <- rbind(comp, data.frame(distance = d, model = m,
moran_I = test$estimate["Moran I statistic"]))
}
}
# keep the order of the models in the legend
comp$model <- factor(comp$model, levels = names(models))
ggplot(comp, aes(x = distance, y = moran_I, col = model)) +
geom_hline(yintercept = 0, linetype = "dashed") +
geom_line() +
geom_point() +
labs(x = "Neighborhood distance (m)", y = "Moran's I of residuals", col = NULL)
The residuals of the linear model and the spatial lag model show nearly the same spatial autocorrelation, with Moran’s I up to about 0.4 at 200 m. In contrast, the residuals of the spatial error model show almost no spatial autocorrelation at any distance. Note that this is partly expected by construction: the residuals of the spatial error model are the errors \(\epsilon\), from which the spatially autocorrelated part (\(\lambda W u\)) has been removed.
We compared a linear regression model, a spatial lag model, and a spatial error model of log-transformed zinc concentration. The spatial error model fitted the data best (AIC = 110.8, compared with 146.6 for the spatial lag model and 147.1 for the linear regression model) and largely removed the spatial autocorrelation from the residuals at all neighborhood distances. The spatial lag model, in contrast, left the residual spatial autocorrelation largely unchanged.