# Spatial Correlation: Consequences, Diagnosis, and Spatial Models

A pricing analyst at a short-term-rental platform, Airbnb-style, regresses the log of the nightly price on capacity and number of bedrooms for 600 entire-home listings in Amsterdam. Both coefficients are very precise. A colleague maps the residuals and sees patches: whole stretches of the city where listings are priced above what the model predicts, and others where they are priced below. The model has not "explained" the neighborhood. Can we still trust the standard errors?

| Coefficient | Estimate | Conventional SE | $t$ | Spatially robust SE (Conley, 1 km) | $t$ |
|---|---|---|---|---|---|
| Capacity (`accommodates`) | 0.088 | 0.018 | 4.82 | 0.021 | 4.12 |
| Bedrooms | 0.124 | 0.025 | 4.90 | 0.029 | 4.34 |

*(Real data: a 600-listing sample of the Inside Airbnb Amsterdam scrape (source: Inside Airbnb, insideairbnb.com, CC BY 4.0), with no listing identifiers; see the data note in the companion notebook. Dependent variable: log nightly price. The coefficient is read approximately as a percentage change: 0.124 means about 12% more per additional bedroom.)*

```{div} full-width
![Map of OLS residuals for 600 Amsterdam listings (left) and the same residuals randomly reassigned across locations (right)](images/spatial_residuals_hook.png)
```

The difference between the two columns is real but modest: robust standard errors are 13–17% larger. The map, on the other hand, leaves no doubt. In the left panel, residuals of the same sign cluster together (Moran's $I = 0.27$, which we define below, with a permutation $p$-value of about 0.001). In the right panel, the same residuals shuffled across locations look like noise. The errors of nearby listings resemble each other, just as, in the section on [serial correlation](2_serial_correlation.md), the errors of nearby weeks did: same problem, with distance instead of time.

Why is the correction here so mild when the dependence is so evident? And what is that pattern telling us about the model? Answering both is the path of this section. As in the previous two, we follow *what OLS preserves, what breaks, how to detect it, and how to fix it*, with a twist that has no counterpart in time series proper: spatial dependence can be a nuisance in the errors or the substantive phenomenon (one zone's promotion lifting its neighbors' orders), and each case calls for a different tool.

---

## 1. Objectives

By the end of this section, you will understand:

- What **spatial correlation** is, where it comes from, and how the **weights matrix** $W$ turns "near" into numbers.
- What OLS preserves and what breaks when errors are spatially correlated, why the damage requires spatial structure in both the errors *and* the regressor, and why the effective sample size is smaller than $N$.
- How to **detect** spatial dependence with residual maps, Moran's I, and the LM-lag and LM-error tests, and why it can be a *symptom* of a misspecified model.
- How to **restore inference** with spatially robust standard errors (Conley, clustering) and when it is also worth modeling the dependence (spatial error model, SEM).
- Why a dependence that is *substantive* (a spatial lag, SAR) makes OLS inconsistent, and how the interpretation of the coefficients changes into direct and indirect effects.
- The limits of spatial analysis: the modifiable areal unit problem and the ecological fallacy.

---

## 2. What Is Spatial Correlation?

In the section on [statistical properties of OLS](../ch1_regresion_simple/3_statistical_properties.md) we assumed that the errors of different observations are uncorrelated. **Spatial correlation** (or spatial autocorrelation) violates that assumption through geography: $\text{Cov}(\varepsilon_i, \varepsilon_j) \neq 0$ when units $i$ and $j$ are close. It is Tobler's first law of geography {cite:p}`tobler1970computer`: "everything is related to everything else, but near things are more related than distant things." When the correlation is positive, similar values cluster (patches of high residuals next to high ones); when it is negative, they alternate like a checkerboard. Positive correlation is by far the most common.

Why would errors be spatially correlated? Almost always for one of three reasons. **Omitted local factors**: neighborhood amenities, a nearby event, competitors' behavior, anything that moves with location and is not in the model ends up in the error, and since it is shared by neighbors, their errors resemble each other. **Spillovers**: what happens in one zone directly affects neighboring zones (a promotion in one area also lifts the next one). And **arbitrary spatial scale**: the unit we observe (a postal code, a delivery zone) may not coincide with the scale at which the phenomenon operates.

There is an obstacle with no counterpart in time series. With $N$ units there are $N^2$ possible pairwise covariances, and we cannot estimate them without imposing a structure. In time there is a natural one (the order), in space we must choose it. Throughout, as in the previous sections, we maintain strict exogeneity: $x_i$ is uncorrelated with every $\varepsilon_j$. We will see that this is a different issue from the one in section 7.3, where the dependence lives in the outcome $y$ itself.

---

## 3. The Weights Matrix $W$

To formalize "near" we define a **spatial weights matrix** $W$, an $N \times N$ matrix in which $w_{ij} > 0$ if unit $j$ is a neighbor of unit $i$, and $w_{ij} = 0$ otherwise (in particular $w_{ii} = 0$). Most entries are zero. There are several ways to define who is a neighbor:

- **Contiguity**: neighbors are units that share a border. On a grid, *rook* contiguity counts those that share a side, and *queen* contiguity also counts those touching at a corner.
- **$k$ nearest neighbors**: each unit's neighbors are the $k$ closest ones, even if they are far away in absolute terms.
- **Distance band**: neighbors are all units within a given radius, with weights that may decay with distance.

```{div} full-width
![Neighbors of a focal zone under rook, queen, and 6-nearest-neighbors definitions on a 7 by 7 grid with small jitter](images/spatial_weights_neighbors.png)
```

It is customary to **row-standardize** $W$, so that each row sums to one. Then $(Wy)_i = \sum_j w_{ij}\,y_j$ is the **spatial lag** of $y$: the average of the values of unit $i$'s neighbors. It is a smoothed version of $y$, and it plays the role that $y_{t-1}$ played in [serial correlation](2_serial_correlation.md): the "nearby" value that can be used as a regressor, with the difference that here the neighbors are on all sides at once.

Some practical warnings. Units at the border of the map have fewer neighbors, which makes their weights differ. Units can end up isolated (islands). The $k$-neighbors relation is not symmetric: $j$ can be among $i$'s nearest neighbors without $i$ being among $j$'s. And, above all, **$W$ is an assumption**, not data: the analyst chooses it. The practical response is not to look for the "true" $W$ but to check that the conclusions do not change under reasonable alternatives.

With $W$ in hand, we can write the spatial analogue of the AR(1) process for the errors. The **spatial error process** is

$$\varepsilon = \lambda\,W\varepsilon + u, \qquad\text{that is,}\qquad \varepsilon = (I - \lambda W)^{-1} u,$$

where $u$ is independent noise and $\lambda$ measures the strength of the dependence: each unit's error is a multiple of the average of its neighbors' errors plus its own noise. If $\lambda = 0$ we are back to independent errors. In section 6 you can see how different $W$'s change what we measure.

---

## 4. Exploring the Consequences via Simulation

Let us put ourselves in the position of someone who knows the truth. A delivery marketplace (DoorDash style) divides a city into square zones on a grid. Weekly orders $y_i$ in zone $i$ respond to local promotion spend $x_i$ with a known true effect, $\beta_1 = 1.5$. Unmeasured local demand (events, neighborhood habits, competitors) is spatially correlated with strength $\lambda$, and promotions tend to be run by area, so spend is also spatially clustered with strength $\rho_x$. We draw that city 2,000 times, estimate by OLS in each, and examine the distribution of the estimates. Before reading the formal results, explore the dashboard with four questions in mind:

1. Leave $\rho_x = 0$ and raise $\lambda$. Does anything change in the distribution of $\hat{\beta}_1$ or in the coverage of the confidence intervals?
2. Now raise $\rho_x$ too. What happens to the ratio between the conventional standard error and the true dispersion of $\hat{\beta}_1$, and to the coverage? In which combination of $(\lambda, \rho_x)$ is it worst?
3. Look at the residual map next to its shuffled benchmark (same residuals, randomly reassigned across zones). Can you see the patches? How does Moran's I of each map compare?
4. Use the scale panel at the bottom: the same data grouped in blocks of $2 \times 2$ and $4 \times 4$ zones. What happens to the apparent dependence (residual Moran's I) and to the ratio between the conventional standard error and the true dispersion?

<div class="dashboard-iframe-wrapper" style="width: 100%; overflow: hidden;">
  <iframe src="https://simuecon.com/spatial_correlation_cost/?lang=en" style="width: 100%; min-height: 500px; border: 0; display: block; overflow: hidden;" scrolling="no" allowfullscreen></iframe>
</div>

### What do we observe?

**The point estimate is unaffected.** The histogram of $\hat{\beta}_1$ stays centered on the true value, whatever the strength of the spatial dependence. OLS remains unbiased.

**But the distribution is wider than we think.** When both the errors and the regressor are spatially clustered, the estimates scatter much more than the conventional standard error suggests, the ratio between the two falls below 1, and the "95%" intervals cover less than 95% of the time. On a $16 \times 16$ lattice with queen neighbors and $\lambda = \rho_x = 0.6$, the conventional standard error is about 76% of the true dispersion and the "95%" interval covers 87% of the time; with $\lambda = \rho_x = 0.9$ coverage falls to about 50%.

**The damage requires spatial structure on both sides.** If the regressor is not clustered ($\rho_x = 0$) or the errors are not ($\lambda = 0$), the problem largely disappears. This is exactly what happened in the opening example: the number of bedrooms of a listing is not spatially clustered, so even with a strong dependence in the errors, the correction was small.

**There are fewer effective observations than rows, and the scale matters.** In the first case above the data behave as if they had about 147 independent observations instead of 256; in the second, about 30. And when the same data are grouped into larger zones, the apparent dependence changes: with $4 \times 4$ blocks (16 zones) the residual Moran's I is close to zero and the standard-error ratio close to 1, but only 16 observations remain, so what we gain in apparent independence we lose in precision. We return to this in section 8.

---

## 5. Formal Results: What Is Preserved and What Breaks

### 5.1 Unbiasedness is preserved

The proof of OLS unbiasedness uses only $E[\varepsilon \mid X] = 0$; it does not need the errors to be independent of each other. Therefore $E[\hat{\boldsymbol\beta} \mid X] = \boldsymbol\beta$ even if the errors follow a spatial error process. The argument is the same as in the sections on [heteroscedasticity](1_heteroscedasticity.md) and [serial correlation](2_serial_correlation.md), and is in the [appendix](#proof-spatial-unbiasedness). This explains why the histogram in the simulation does not shift.

### 5.2 Conventional standard errors are wrong

With errors of covariance matrix $\Sigma = \text{Var}(\varepsilon \mid X)$, the correct variance of OLS is the sandwich

$$\text{Var}(\hat{\boldsymbol\beta} \mid X) = (X'X)^{-1}\,X'\Sigma X\,(X'X)^{-1},$$

whereas the conventional formula assumes $\Sigma = \sigma^2 I$ and reports $\sigma^2 (X'X)^{-1}$. For the spatial error process,

$$\Sigma = \sigma_u^2\,\big[(I - \lambda W)'(I - \lambda W)\big]^{-1},$$

whose off-diagonal terms are nonzero for neighboring units. The derivation is in the [appendix](#proof-spatial-variance). In the simple regression, the off-diagonal terms are multiplied by cross-products $(x_i - \bar{x})(x_j - \bar{x})$ of neighbors: if $x$ is spatially clustered, neighbors have deviations of the same sign, those cross-products are positive, and the cross-covariances add up instead of canceling out. That is why the damage requires clustering on both sides.

Unlike the AR(1) case in the previous section, there is no tidy closed-form factor on a general lattice: the exact variance depends on $W$, on $\lambda$, and on the specific arrangement of $x$. We can still define the **effective sample size** exactly as before, as the number of independent observations that would give the same precision, $N_{\text{eff}} = N\,(\overline{SE}_{\text{conv}}/SD_{\text{true}})^2$, and the dashboard reports it computed by simulation. **Sign of the distortion:** with positive dependence in the errors and positive clustering in the regressor, the conventional standard error understates the uncertainty. With negative dependence it can overstate it, and if either dimension has no structure, the conventional formula is approximately correct.

### 5.3 Efficiency is lost

The Gauss-Markov Theorem requires uncorrelated errors. With spatial correlation OLS remains linear and unbiased, but it is no longer the minimum-variance linear unbiased estimator: the residuals of neighbors contain information about each other's errors that OLS wastes. The Generalized Least Squares (GLS) estimator, which weights by $\Sigma^{-1}$, exploits it; we will see its feasible version in section 7.2.

### 5.4 Dependence in $y$ is not dependence in the errors

An important conceptual point. The variable $y$ can be strongly spatially autocorrelated, with a high Moran's I, while the regression residuals show no dependence at all: if the covariates already explain the geographic pattern (for example, prices are high near the center and the model includes distance to the center), nothing is left over in the errors. Conversely, a significant Moran's I *in the residuals* says something specific about the model: either there is a missing variable that varies spatially, or there is an interaction structure we have not modeled. That is why we always diagnose on the residuals, not on $y$.

---

## 6. Diagnosing Spatial Correlation

Before defining the tests, the following dashboard lets you see what the different tools "look like." It generates data under five processes: no dependence, spatial error (SEM), spatial lag (SAR), omitted spatial covariate, and heteroscedasticity (the "true $W$" selector appears for the two spatial processes). Explore these questions:

1. Change the analyst's $W$ (rook, queen, nearest neighbors, distance band) and the zone to inspect (corner, edge, center): how many neighbors does it have and with what weight? Compare $y$ with its spatial lag $Wy$. How are they different?
2. Read the Moran scatterplot and the permutation distribution under each scenario. In which ones does the cloud tilt upward and the observed $I$ fall far from the reshuffled values?
3. Compare the scenarios with no spatial process in the errors (omitted covariate, heteroscedasticity) with spatial error and spatial lag. Which tests reject in each? Then switch between spatial error and spatial lag and watch the two robust tests.
4. Set the true $W$ to 4 nearest neighbors, the strength to 0.3, and change the analyst's $W$. What happens to the power of the tests?

<div class="dashboard-iframe-wrapper" style="width: 100%; overflow: hidden;">
  <iframe src="https://simuecon.com/spatial_correlation_diagnostics/?lang=en" style="width: 100%; min-height: 500px; border: 0; display: block; overflow: hidden;" scrolling="no" allowfullscreen></iframe>
</div>

### 6.1 Residual maps

The first diagnostic is to look. Map the OLS residuals with a diverging color scale (red positive, blue negative) and compare with a random reshuffling of the same residuals, as in the figure that opened the section. Patches of the same sign indicate positive dependence; if the signs alternate more than they should, negative dependence. It costs nothing, and it is what the residual-map panel of the first dashboard shows.

### 6.2 Moran's I

**Moran's I** {cite:p}`moran1950notes` is the spatial analogue of the first-order autocorrelation of the residuals. With $z_i = e_i - \bar{e}$ the deviations of the variable of interest and $S_0 = \sum_{i,j} w_{ij}$,

$$I = \frac{N}{S_0}\,\frac{\sum_{i}\sum_{j} w_{ij}\,z_i z_j}{\sum_i z_i^2}$$

(with row-standardized $W$, $S_0 = N$ and $I = z'Wz / z'z$). Under the null of no spatial autocorrelation, the expected value is $E[I] = -1/(N-1)$, approximately zero (the [appendix](#proof-moran) shows it). Positive values mean neighbors have similar values, negative values mean they are dissimilar. Inference is usually done by **permutation**: the values are reassigned randomly across locations many times, $I$ is recomputed each time, and the observed value is compared with that distribution.

The **Moran scatterplot** plots $Wz$ against $z$. The slope of the fitted line is, with row-standardized $W$, exactly $I$, and the quadrants identify high-high and low-low (clusters) and high-low and low-high (outliers) zones.

Three caveats matter. Applied to OLS residuals, the null distribution changes slightly, so the residual version is used. Moran's I is a *misspecification statistic*: it also reacts to an omitted variable with spatial structure or a neglected nonlinearity, not only to genuine spatial dependence (pure heteroscedasticity, in contrast, leaves it almost untouched, as the dashboard shows). And its value depends on the chosen $W$ (values computed with different weights are not comparable).

### 6.3 LM tests: lag or error?

Moran's I tells us there is something spatial; it does not say what. The **Lagrange multiplier (LM) tests** {cite:p}`anselin1996simple` use only the OLS residuals to test two specific alternatives. With $e$ the residuals, $\hat\sigma^2 = e'e/N$ and $T = \text{tr}(W'W + W^2)$,

$$LM_{\text{error}} = \frac{(e'We/\hat\sigma^2)^2}{T} \;\overset{a}{\sim}\; \chi^2(1), \qquad LM_{\text{lag}} = \frac{(e'Wy/\hat\sigma^2)^2}{D_\rho} \;\overset{a}{\sim}\; \chi^2(1),$$

where $D_\rho = (WX\hat{\boldsymbol\beta})'M(WX\hat{\boldsymbol\beta})/\hat\sigma^2 + T$ and $M = I - X(X'X)^{-1}X'$. The first tests dependence in the errors (SEM); the second, dependence in the outcome (spatial lag, SAR). The problem is that each reacts to the other alternative as well. The **robust** versions of each test correct for the presence of the other, and they are the ones used to decide. The practical rule: if only one rejects, that is the direction; if both reject, follow the larger robust statistic.

| Test | Null | Alternative | Reacts also to |
|---|---|---|---|
| **Moran's I** (residuals) | No spatial autocorrelation | Any | Omitted spatial variables, neglected nonlinearity; its power depends on $W$ |
| **LM-error** | $\lambda = 0$ | Spatial error | Spatial lag (non-robust version) |
| **LM-lag** | $\rho = 0$ | Spatial lag | Spatial error (non-robust version) |
| **Robust LM-error / LM-lag** | Same, correcting for the other alternative | Same | Less sensitive to the other alternative |

**What the dashboard shows.** With no dependence every test rejects between 4% and 7% of the time, close to the nominal 5%. Under a spatial error with strength 0.6, LM-error and its robust version reject in essentially every simulated city, while robust LM-lag rejects in only 17%: the robust pair points to the error. Under a spatial lag the picture is less clean (robust LM-lag rejects always, but robust LM-error rejects in 87%), which is why the rule is to follow the *larger* statistic, not to wait for only one to reject. With an omitted spatial covariate Moran and all LM tests reject in nearly every city even though there is no spatial process in the errors: they signal misspecification, not a dependence structure. Pure heteroscedasticity, in contrast, does not fool them here. Finally, the matrix matters most when the dependence is weak: with a spatial error of strength 0.3 on a 4-nearest-neighbors structure, Moran's I rejects in 93% of the cities with the right $W$ and in 81% to 90% with the others.

<div class="jupyterlite-embed-wrapper" data-paid-gated="true"
     data-lite-url="_jupyterlite/notebooks/index.html?path=3_spatial_correlation_notebook.ipynb"
     data-button-label="💻 How to Estimate in Code"></div>

Part 1 of the notebook builds $W$ on real listings, draws the Moran scatterplot with permutation inference, and computes the LM tests, in two cities.

### 6.4 Spatial dependence as a symptom

Before modeling the dependence, ask why it is there. In the opening example, the residual map shows a pattern: the central listings are above the line and the peripheral ones below. That is not mysterious dependence between neighbors; it is a missing variable, the distance to the center. Adding it cuts the Moran's I of the Amsterdam residuals from 0.27 to 0.09, and the robust LM-error statistic from 139 to 13. This connects with what we saw in the section on [omitted variable bias](../ch2_regresion_multiple/1_multiple_regression.md), exactly as in serial correlation: an incomplete specification shows up as a pattern in the residuals. Zone fixed effects, amenities, or local characteristics can play the same role. Only when dependence persists after specifying the model properly do we need the tools in the next section.

---

## 7. The Fix: Robust Inference and Spatial Models

There are three responses, in increasing order of ambition: **(i)** keep OLS but correct the standard errors (Conley, clustering); **(ii)** model the dependence in the errors to gain efficiency (spatial error model); **(iii)** if the dependence is substantive, model it (spatial lag or SLX). Before seeing the formulas, the following dashboard compares estimators in the error mode (spatial dependence as nuisance). Explore:

1. Which estimators keep the right center of the distribution of $\hat{\beta}_1$? Which have "honest" standard errors (close to the true dispersion)? Which is the most precise?
2. Try a small city (few zones) with high $\lambda$: what happens to the coverage of each estimator?
3. Change the Conley cutoff and read the sensitivity panel. What happens to the coverage when it is too short?
4. Compare the standard errors of the four methods with the true dispersion of the estimates: which methods only fix the standard error and which also reduce the dispersion?

<div class="dashboard-iframe-wrapper" style="width: 100%; overflow: hidden;">
  <iframe src="https://simuecon.com/spatial_correlation_fixes/?lang=en&mode=error" style="width: 100%; min-height: 500px; border: 0; display: block; overflow: hidden;" scrolling="no" allowfullscreen></iframe>
</div>

**What do we observe?** On a $16 \times 16$ lattice with $\lambda = \rho_x = 0.9$, the conventional interval covers about 50%; Conley with a cutoff of 1, 2, and 4 cells covers 48%, 64%, and 76%; clustering by $4 \times 4$ blocks, 84%; and maximum likelihood for the spatial error model, 94%. All four are centered on the true value, but the first three have the same dispersion (0.18), while the model-based estimator has a third of it (0.06). Robust standard errors repair the inference; only modeling the dependence also improves precision, and then only if the model is right. The correction also depends on the cutoff, and with few zones nothing is free: at $L = 12$ with $\lambda = 0.9$ every method struggles.

### 7.1 Spatially Robust Standard Errors

The idea is the same as in the heteroscedasticity and serial-correlation cases: keep the OLS point estimates and replace the variance estimator with one that does not impose independence. **Conley's** estimator (spatial HAC) {cite:p}`conley1999gmm` includes the covariances between the scores of nearby units, down-weighted by distance:

$$\widehat{\text{Var}}_{\text{Conley}}(\hat{\boldsymbol\beta}) = (X'X)^{-1}\left[\sum_{i}\sum_{j} K\!\left(\frac{d_{ij}}{h}\right) e_i\,e_j\,\mathbf{x}_i\mathbf{x}_j'\right](X'X)^{-1}, \qquad K(u) = (1-u)_+,$$

where $d_{ij}$ is the distance between units and $K$ is the Bartlett kernel, as in Newey-West: pairs farther apart than the **cutoff** $h$ receive zero weight (the dashboard applies the kernel to the distance in each coordinate separately and multiplies them, which guarantees a valid, positive semidefinite estimator). Choosing $h$ is the analogue of choosing the bandwidth $L$ in time. If it is too short it ignores relevant covariances and the standard error falls short, as the sensitivity panel shows; if too long, it includes too many noisy products and makes the estimator volatile, which becomes visible in small cities.

A simpler alternative is **clustering** by region: allow arbitrary correlation within each region (neighborhood, administrative area) and none between regions. It is the same idea with a grouping structure instead of a distance, and it is a good default when there are enough regions and dependence does not cross their borders. Its full treatment (choosing the clustering level, few clusters, the Moulton problem) belongs to the section on panel data. Robust errors have limits, as always: they are asymptotic, they need enough units, they depend on the cutoff or the grouping, and they do not correct OLS's inefficiency. Note that `statsmodels` has no built-in Conley estimator, so the notebook shows a short custom implementation.

```{admonition} 💻 How to Estimate in Code
:class: dropdown

Part 2 of the same notebook compares conventional, clustered, and Conley standard errors on the Amsterdam listings for several cutoffs, and runs a small coverage simulation on a frozen lattice with the dashboards' DGP.
```

### 7.2 The Spatial Error Model (SEM)

If we believe the dependence lives in the errors, we can model it:

$$y = X\boldsymbol\beta + \varepsilon, \qquad \varepsilon = \lambda W\varepsilon + u.$$

Under this model OLS remains unbiased but inefficient. The **spatial error model** is estimated by maximum likelihood (or by feasible GLS and GMM, {cite:p}`kelejian1998generalized`), which accounts for the structure $\Sigma$ and gains efficiency, as Cochrane-Orcutt did in time. The interpretation of $\boldsymbol\beta$ is unchanged: it is the same marginal effect, estimated more precisely, and $\lambda$ is a *nuisance parameter*. As with FGLS, the gain depends on the error model being the right one, so SEM is used as a robustness check alongside robust standard errors, not as a substitute.

### 7.3 The Spatial Lag Model (SAR): when dependence is the outcome

Now suppose the dependence is not a nuisance: what happens in one zone *causes* what happens in its neighbors. A promotion that raises orders in one zone also raises them in the adjacent ones, and those in turn raise the first, in a feedback chain. The **spatial lag model** (SAR) is

$$y = \rho\,Wy + X\boldsymbol\beta + \varepsilon,$$

with reduced form $y = (I - \rho W)^{-1}(X\boldsymbol\beta + \varepsilon)$. This is the spatial equivalent of putting $y_{t-1}$ in the model, and it comes with the same danger as in section 6.4 of the [previous section](2_serial_correlation.md): the regressor $Wy$ depends on the errors of the neighbors, which in turn depend on $y_i$, so $\text{Cov}(Wy, \varepsilon) \neq 0$ and OLS is **inconsistent**. And if we leave $Wy$ out and regress $y$ on $x$ only, we commit an omitted variable bias: the coefficient on $x$ absorbs part of the spillovers. Explore this in the dashboard, now in the lag mode:

1. What happens to the OLS estimate as the spillover $\rho$ grows? Does it improve with a larger number of zones? Watch the coverage panel as $L$ goes from 12 to 20.
2. Which estimators recover the coefficient? Compare the last column of the table (implied total effect) with the true value stated below it.
3. Look at the spillover map and the effect by ring of distance: how far does the effect of a local promotion reach, and how is it split between direct effect and spillovers?

<div class="dashboard-iframe-wrapper" style="width: 100%; overflow: hidden;">
  <iframe src="https://simuecon.com/spatial_correlation_fixes/?lang=en&mode=lag" style="width: 100%; min-height: 500px; border: 0; display: block; overflow: hidden;" scrolling="no" allowfullscreen></iframe>
</div>

**What do we observe?** With $\rho = 0.4$, OLS averages 1.76 instead of 1.5 and the bias is the same with 144, 256, or 400 zones: more data do not help, and the coverage of its "95%" interval *falls* from 28% to 2% as the lattice grows, because the standard error shrinks around the wrong value. SLX has a small bias (+0.04) and captures local spillovers, but its total effect (2.36) is below the true 2.50. ML and 2SLS recover the coefficient and the total effect (2.49 and 2.51). Here 2SLS is only slightly noisier than ML because $x$ is itself clustered, which makes $Wx$ and $W^2x$ strong instruments. And the effect map shows what the coefficient hides: a promotion in the central zone yields a direct effect of 1.54 and 0.96 more spread across neighbors, almost all within the first ring.

The solution is to estimate SAR properly: by **maximum likelihood**, which takes the feedback into account, or by **two-stage least squares** with the spatial lags of the covariates, $WX$ and $W^2X$, as instruments for $Wy$ {cite:p}`kelejian1998generalized`. The 2SLS estimator inherits the usual weak-instrument problem (see the section on [weak instruments](../ch4_inferencia_causal/5_iv_2sls.md)): it works only if $x$ is itself spatially structured, so that $WX$ moves $Wy$.

**The interpretation shift.** In SAR, $\beta_1$ is no longer the marginal effect of $x$ on $y$. Since $y = (I - \rho W)^{-1}(X\beta + \varepsilon)$, the effect of changing $x_j$ on $y_i$ is the $(i,j)$ entry of the matrix $(I - \rho W)^{-1}\beta_1$. Its diagonal gives the **direct effect** (on the zone itself, including the feedback from neighbors); its off-diagonal entries are the **indirect effects** or spillovers; and the sum of both is the **total effect**. With row-standardized $W$, the average total effect is $\beta_1/(1-\rho)$ {cite:p}`lesage2009introduction`. The dashboard shows that map: a promotion in the central zone lifts orders in the neighboring zones, with an effect that fades with distance.

### 7.4 SLX, Durbin, and how to choose

A simpler way to allow for spillovers is the **SLX** model, $y = X\boldsymbol\beta + WX\boldsymbol\theta + \varepsilon$: the covariates of the neighbors affect the outcome, with no feedback. It is estimated by plain OLS and captures *local* spillovers. The **spatial Durbin model** combines $Wy$ and $WX$. How do we choose? The model should start from theory: is the interaction substantive or a nuisance? Are spillovers local or global? The LM tests and the robustness checks support that decision; they are not an automatic search. The real data of the opening example illustrate it: in the Amsterdam sample the residual dependence leans toward the error model (robust LM-error much larger than LM-lag), while in a Barcelona sample it leans toward the lag model; the notebook shows both.

```{admonition} 💻 How to Estimate in Code
:class: dropdown

Part 3 of the same notebook estimates SEM, SAR, and SLX on both cities, shows the direct, indirect, and total effects, and includes a cautionary example about instrument strength in 2SLS.
```

---

## 8. Limits and Cautions

Spatial analysis has its own pitfalls, which arise from the units we observe. The **modifiable areal unit problem** (MAUP) {cite:p}`openshaw1984maup` refers to the fact that results depend on the scale and the zoning chosen: the same data grouped in $2 \times 2$ or in $4 \times 4$ blocks show different correlations, different slopes, and a different effective number of observations, as the scale panel of the first dashboard shows. There is no "correct" grouping, so it is good practice to report results at more than one scale.

The **ecological fallacy** is inferring individual behavior from aggregate data: a relationship between two zone averages does not imply that the relationship holds for the people or businesses within them. And **change of support** arises when point data (listings) and areal data (zones) are mixed without care. Finally, a reminder in the spirit of this chapter: spatial effects do not always change the conclusions, as the opening example showed. Diagnose, report robust inference, and let the evidence, not the method, determine how far to go.

---

## 9. Summary and Decision Guide

Spatial correlation does not invalidate the OLS point estimates under strict exogeneity and dependence in the errors, but it compromises inference and efficiency, and when the dependence is substantive it also compromises the estimator. The following path summarizes recommended practice:

1. **Always map** the residuals.
2. **Compute Moran's I of the residuals** and the LM tests (robust versions included) with a few reasonable weights matrices.
3. **First ask whether something is missing from the model:** distance to the center, local characteristics, zone fixed effects. Adding it is often better than correcting standard errors.
4. **If dependence persists:** use spatially robust standard errors (Conley, or clustered by region) by default.
5. **If efficiency matters** and the dependence is a nuisance: consider the spatial error model, and report OLS with robust errors as a robustness check.
6. **If spillovers are the substantive question:** estimate SAR, SLX, or Durbin, interpret direct and indirect effects, and remember that OLS is inconsistent under a spatial lag.
7. **Report sensitivity to $W$.**

Under strict exogeneity and dependence in the errors, OLS point estimates are not discarded: only the quantification of uncertainty changes. The same idea, units that resemble each other and effective information smaller than $N$, returns when the dependence is by group (users in the same city), where clustered errors and panel data take over, and in the causal-inference sections, where interference between treated and control units can break the independence of potential outcomes.

---

## Appendix: Formal Derivations

(proof-spatial-unbiasedness)=
### A.1 OLS Unbiasedness Does Not Require Independent Errors

**Step 1 —** Substituting $y = X\boldsymbol\beta + \varepsilon$ into the OLS formula:

$$\hat{\boldsymbol\beta} = (X'X)^{-1}X'y = \boldsymbol\beta + (X'X)^{-1}X'\varepsilon$$

**Step 2 —** Take the conditional expectation given $X$:

$$E[\hat{\boldsymbol\beta} \mid X] = \boldsymbol\beta + (X'X)^{-1}X'\,E[\varepsilon \mid X]$$

**Step 3 —** Under strict exogeneity, $E[\varepsilon \mid X] = 0$, and the second term vanishes. No step used that the off-diagonal entries of $\text{Var}(\varepsilon \mid X)$ are zero: unbiasedness holds even if the errors are correlated across space.

(proof-spatial-variance)=
### A.2 Variance of $\hat{\boldsymbol\beta}$ with Spatial Error Dependence

**Step 1 —** From A.1, $\hat{\boldsymbol\beta} - \boldsymbol\beta = (X'X)^{-1}X'\varepsilon$. Since $(X'X)^{-1}X'$ is nonrandom given $X$:

$$\text{Var}(\hat{\boldsymbol\beta} \mid X) = (X'X)^{-1}X'\,\Sigma\,X(X'X)^{-1}, \qquad \Sigma = \text{Var}(\varepsilon \mid X)$$

**Step 2 —** In the spatial error process, $\varepsilon = (I-\lambda W)^{-1}u$ with $\text{Var}(u) = \sigma_u^2 I$. Then

$$\Sigma = (I-\lambda W)^{-1}\,\sigma_u^2 I\,\big[(I-\lambda W)^{-1}\big]' = \sigma_u^2\,\big[(I-\lambda W)'(I-\lambda W)\big]^{-1}$$

**Step 3 —** If $\lambda = 0$, $\Sigma = \sigma_u^2 I$ and the sandwich collapses to the conventional $\sigma_u^2(X'X)^{-1}$. If $\lambda \neq 0$, $\Sigma$ has nonzero off-diagonal entries for units connected by $W$ (directly or through chains of neighbors), and the product $X'\Sigma X$ weights them by the cross-products of the regressors of the connected units. If $X$ is not spatially structured, those cross-products tend to cancel and the sandwich is close to the conventional formula; if $X$ is clustered, they add up. The ratio between the true variance and the conventional one defines, via $N_{\text{eff}} = N\,(\overline{SE}_{\text{conv}}/SD_{\text{true}})^2$, the effective sample size.

(proof-moran)=
### A.3 Expected Value of Moran's I Under the Null

**Step 1 —** Under the null of no spatial autocorrelation (with the permutation or randomization argument), every assignment of the observed values $z_1, \dots, z_N$ to the locations is equally likely. Therefore, for $i \neq j$, $E[z_i z_j] = \frac{1}{N(N-1)}\sum_{k \neq l} z_k z_l$.

**Step 2 —** With $\sum_k z_k = 0$ (deviations from the mean), $\sum_{k \neq l} z_k z_l = \big(\sum_k z_k\big)^2 - \sum_k z_k^2 = -\sum_k z_k^2$, so $E[z_i z_j] = -\dfrac{\sum_k z_k^2}{N(N-1)}$.

**Step 3 —** The denominator $\sum_i z_i^2$ is the same in every permutation. Taking the expectation of the numerator and using $w_{ii} = 0$:

$$E\left[\sum_{i}\sum_{j} w_{ij}\,z_i z_j\right] = S_0\cdot\left(-\frac{\sum_k z_k^2}{N(N-1)}\right)$$

Hence $E[I] = \dfrac{N}{S_0}\cdot\dfrac{S_0\,\big(-\sum_k z_k^2/(N(N-1))\big)}{\sum_i z_i^2} = -\dfrac{1}{N-1}$, which tends to zero as $N$ grows.

---

## Test what you learned

<div class="quiz-widget" data-quiz-slug="ch3-spatial-correlation"></div>

## References

```{bibliography}
:filter: docname in docnames
```
