Spatial Econometrics in Python and R: Moran's I, SAR, SEM, and SDM Guide
Unprojected degree coordinates and raw regression coefficients distort spatial econometric analysis. Here is how to construct valid spatial weights, run specification tests, and report true spillover impacts.
HumanPen Team
· 15 min read
Direct Answer: How to Avoid Coordinate Distortion and Misspecification in Spatial Econometrics
Spatial econometric models fail when empirical researchers commit two fundamental methodological errors: calculating distance metrics or spatial weights in unprojected angular degrees (`EPSG:4326`), and interpreting raw regression coefficients from spatial lag (`SAR`) or Spatial Durbin (`SDM`) models as marginal effects. Valid spatial econometrics requires reprojecting vector boundaries into an equal-area or conformal planar coordinate reference system (`CRS`) measured in meters, defining row-standardized spatial weights matrices (`W`) while explicitly handling disconnected island units, running Anselin's Rao score diagnostics (`spdep::lm.RStests`), and calculating LeSage & Pace (2009) average direct, indirect (spillover), and total impacts through matrix trace approximations.
"The coordinate reference system (CRS) is important because the geometric shapes in a GeoSeries or GeoDataFrame object are simply a collection of coordinates in an arbitrary space. A CRS tells Python how those coordinates relate to places on the Earth."
For researchers in regional science, urban economics, environmental policy, and public health, spatial dependence is not a mere statistical nuisance; it reflects genuine spatial interaction, geographic spillover, and shared regional shocks. When spatial autocorrelation is present in cross-sectional or panel data, standard Ordinary Least Squares (`OLS`) estimators become biased, inefficient, or inconsistent depending on whether the spatial process operates through the dependent variable, omitted disturbance terms, or exogenous covariates. Implementing spatial workflows in modern Python (`geopandas` `v1.2.0`, `libpysal` `v4.15.1`, `esda` `v2.10.0`, `spreg` `v1.9.2`) and R (`sf` `v1.1-3`, `spdep` `v1.4-3`, `spatialreg` `v1.4-3`) requires a systematic progression from geometric projection to spatial weights construction, global and local autocorrelation diagnostics, model selection, and scalar impact estimation.
Projected Coordinate Systems and Spatial Weights Matrix Construction
The most prevalent geometric error in spatial data analysis occurs when researchers construct spatial weights or compute geometric centroids directly from unprojected geographic coordinates (`EPSG:4326` / `WGS 84`). Unprojected datasets store locations in angular degrees of latitude and longitude. Because meridians converge toward the poles, the linear ground distance represented by one degree of longitude shrinks by `cos(latitude)`, dropping from approximately 111.32 km at the equator to roughly 55.8 km at 60 degrees North. In Python `geopandas`, executing `gdf.geometry.centroid`, `libpysal.weights.DistanceBand.from_dataframe(gdf, threshold=...)`, or `KNN.from_dataframe(gdf, k=5)` on an `EPSG:4326` dataset emits a warning and treats spherical degrees as planar Euclidean distances, severely stretching East–West spatial relationships at mid and high latitudes. Applied researchers must reproject vector layers into equal-area or conformal planar coordinate systems measured in meters—such as `EPSG:5070` or `ESRI:102003` (Albers Equal Area for the contiguous United States), `EPSG:3035` (ETRS89-extended / LAEA for Europe), or `EPSG:4547` (CGCS2000 Gauss-Kruger for China)—or derive a local UTM zone using `gdf.estimate_utm_crs()` before computing geometric relationships.
"Spatial coordinates either refer to projected (or Cartesian) coordinates, meaning that they are associated to points on a flat space, or to unprojected or geographic coordinates, when they refer to angles (latitude, longitude) pointing to locations on a sphere (or ellipsoid)."
Once polygon boundaries reside in a projected planar CRS, analysts construct the spatial weights matrix `W` to operationalize geographic proximity. Boundary contiguity matrices fall into two primary standards: Rook contiguity, where two polygons must share a common linear edge of length greater than zero, and Queen contiguity, where polygons are considered neighbors if they share either a linear boundary or a single corner vertex point. For general irregular administrative regions such as counties or census tracts, Queen contiguity (`libpysal.weights.Queen.from_dataframe(gdf, use_index=True)` in Python or `spdep::poly2nb(sf_obj, queen = TRUE)` in R) represents the standard default because it prevents artificial disconnections caused by digitization artifacts at four-corner intersections. In empirical regressions, `W` is typically row-standardized (`w.transform = "R"` in PySAL, `nb2listw(nb, style = "W")` in `spdep`), scaling each non-empty row such that `sum_j w_ij = 1`. Row-standardization converts the spatial lag `(W y)_i = sum_j w_ij y_j` into an intuitive weighted average of neighboring outcomes and bounds the characteristic roots of `W` so that the spatial autoregressive parameter `ρ` lies strictly within `(1 / omega_min, 1)`.
- 1. Reproject before computing distance or contiguity: Always transform raw vector shapefiles from angular degree systems into metric projected coordinate systems using `to_crs()` in GeoPandas or `st_transform()` in R before calculating centroids, distance thresholds, or neighbor graphs.
- 2. Select contiguity conventions thoughtfully: Adopt Queen contiguity as the baseline for polygonal administrative geographies to ensure corner-touching units remain connected, switching to Rook only when theoretical mechanisms require strict shared linear boundaries.
- 3. Account for island units explicitly: When geographic datasets include islands or disconnected administrative units with zero contiguity neighbors, `spdep` halts execution unless `zero.policy = TRUE` is explicitly passed to `nb2listw()`, `moran.test()`, `lagsarlm()`, and `impacts()`.
- 4. Utilize k-nearest neighbors for guaranteed connectivity: When study areas contain irregular archipelagos or remote enclaves, replace contiguity weights with `k`-nearest neighbors (`KNN.from_dataframe(gdf, k=6)` or `knn2nb(knearneigh(coords, k = 6))`) to guarantee each observation receives exactly `k` neighbors, applying `make.sym.nb()` when estimation algorithms require symmetric spatial weights.
Global Moran's I and Local LISA: Spatial Autocorrelation Diagnostics
Before specifying spatial regression equations, empirical researchers evaluate whether geographic dependence exists using Global Moran's `I`. Formulated as the spatial analogue of the Pearson product-moment correlation coefficient, Global Moran's `I` assesses whether high values cluster near other high values and low values near low values across the entire study domain. Under the null hypothesis of complete spatial randomness, the expected value of Moran's `I` is `E[I] = -1 / (N - 1)`, which approaches zero as sample size `N` expands. Moran's `I` is calculated as `I = (N / S_0) × [sum_i sum_j w_ij (y_i - y_bar)(y_j - y_bar)] / [sum_i (y_i - y_bar)^2]`, where `S_0 = sum_i sum_j w_ij`. Under row-standardization with zero island units, `S_0` equals `N`, simplifying the scaling factor `N / S_0` to exactly `1`. A statistically significant positive Moran's `I` indicates positive spatial autocorrelation (spatial clustering), whereas a significant negative coefficient indicates spatial dispersion (a checkerboard pattern).
While Global Moran's `I` yields a single aggregate summary statistic for the entire study area, it masks regional heterogeneity and localized spatial clustering. To identify localized geographic concentrations, Luc Anselin (1995) introduced Local Indicators of Spatial Association (`LISA`), implemented via `esda.Moran_Local(y, w, permutations=999)` in PySAL and `spdep::localmoran()` in R. Local Moran's `I_i` decomposes the global autocorrelation coefficient into individual regional contributions, categorizing statistically significant spatial configurations into four distinct quadrants: High–High (`HH`, hot spots where elevated values are surrounded by elevated values), Low–Low (`LL`, cold spots where low values are surrounded by low values), High–Low (`HL`, spatial outliers where elevated values are surrounded by low values), and Low–High (`LH`, spatial outliers where low values are surrounded by elevated values).
In spatial cluster analysis across thousands of regional units (such as 3,000 counties), evaluating unadjusted pseudo p-values at the 0.05 threshold generates approximately 150 false-positive clusters under complete spatial randomness (`0.05 × 3,000 = 150`), necessitating False Discovery Rate (`FDR`) adjustments (`p.adjust(..., method = "fdr")` or `esda.fdr`).
When reporting LISA cluster maps in journal submissions, empirical researchers must distinguish between exploratory geographic description and formal causal econometrics. Overlaying LISA classifications on standardized choropleth maps reveals geographic fault lines, regional industrial agglomerations, and cross-border policy spillover boundaries. To ensure that visualizations meet peer-reviewed editorial standards, researchers should configure map projections, font hierarchies, and accessible color scales according to our publication-ready scientific charts guide. If significant global or local autocorrelation is confirmed, standard OLS assumption of independent and identically distributed error terms is violated, requiring the researcher to proceed to formal spatial econometric model specification tests.
Spatial Regression Taxonomy: SLX, SAR, SEM, SDM and LeSage-Pace Impact Decomposition
When moving from exploratory spatial data analysis to formal regression modeling, applied econometrics distinguishes among five primary linear specifications based on the structural location of spatial interaction: Ordinary Least Squares (`OLS`), Spatially Lagged X (`SLX`), Spatial Autoregressive / Spatial Lag (`SAR`), Spatial Error Model (`SEM`), and Spatial Durbin Model (`SDM`). The simplest extension is the `SLX` specification (`y = X β + W X θ + ε`), which incorporates exogenous neighborhood characteristics `W X` alongside focal covariates `X` and is consistently estimated via standard OLS. When dependent outcomes exhibit direct peer-to-peer behavioral feedback or geographic contagion, the Spatial Lag Model (`SAR`: `y = ρ W y + X β + ε`) introduces an endogenous spatial lag `W y`, requiring Maximum Likelihood (`spreg.ML_Lag` in Python, `spatialreg::lagsarlm` in R) or Instrumental Variables / Generalized Method of Moments (`spreg.GM_Lag`). If spatial dependence arises instead from unobserved geographic shocks or omitted spatially correlated variables, the Spatial Error Model (`SEM`: `y = X β + u`, where `u = λ W u + ε`) models spatial autoregression in the disturbance vector. Combining both endogenous outcomes and exogenous contextual lags yields the Spatial Durbin Model (`SDM`: `y = ρ W y + X β + W X θ + ε`), which nests both `SAR` (`θ = 0`) and `SEM` (`θ + ρ β = 0`) as testable linear restrictions.
"The statistics are the simple RS test for error dependence (“RSerr”), the simple RS test for a missing spatially lagged dependent variable (“RSlag”), variants of these adjusted for the presence of the other (“adjRSerr” tests for error dependence in the possible presence of a missing lagged dependent variable, “adjRSlag” the other way round), and a portmanteau test (“SARMA”, in fact “RSerr” + “adjRSlag”)."
| Model Specification and Package Routines | Structural Equation | Nature of Spatial Interaction | Estimation Technique | Diagnostic and Selection Criteria |
|---|---|---|---|---|
| Standard OLS (statsmodels, lm) | y = X β + ε | Assumes zero spatial interaction; observations are cross-sectionally independent | Ordinary Least Squares | Baseline benchmark; rejected when Moran's I on OLS residuals is statistically significant |
| Spatially Lagged X / SLX (lmSLX, spreg.OLS) | y = X β + W X θ + ε | Local exogenous spillovers; neighboring X directly shifts focal y | Ordinary Least Squares | Flexible baseline for purely local spillovers; requires no matrix inversions or feedback loops |
| Spatial Autoregressive / SAR (lagsarlm, spreg.ML_Lag) | y = ρ W y + X β + ε | Endogenous global spillover; neighboring outcomes directly feedback into focal y | Maximum Likelihood or Instrumental Variables / GMM | Selected when RSlag or adjRSlag diagnostics reject null; exhibits global spatial diffusion |
| Spatial Error Model / SEM (errorsarlm, spreg.ML_Error) | y = X β + u with u = λ W u + ε | Spatially correlated omitted variables and regional disturbance shocks | Maximum Likelihood or Generalized Moments (GM_Error) | Selected when RSerr or adjRSerr diagnostics reject; regression coefficients β remain directly marginal |
| Spatial Durbin Model / SDM (lagsarlm Durbin=TRUE, ML_Lag) | y = ρ W y + X β + W X θ + ε | Global endogenous feedback plus local exogenous contextual spillovers | Maximum Likelihood (lagsarlm) or Instrumental Variables | General nesting specification; testable against SAR (θ = 0) and SEM (θ + ρ β = 0) via Likelihood Ratio tests |
"The calculation of impacts for spatial lag and spatial Durbin models is needed in order to interpret the regression coefficients correctly, because of the spillovers between the terms in these data generation processes (unlike the spatial error model). Methods for “SLX” and Bayesian fitted models are also provided, the former do not need MC simulations, while the latter pass through MCMC draws."
The most critical trap in spatial econometrics—and the leading cause of manuscript rejection by academic reviewers—is reporting raw regression coefficients `β_k` and `θ_k` from `SAR` or `SDM` estimations as if they represented direct marginal effects. In models containing an endogenous spatial lag `W y`, solving for the reduced form yields `y = (I_N - ρ W)^(-1) (X β + W X θ + ε)`. Because the spatial multiplier matrix `(I_N - ρ W)^(-1) = I_N + ρ W + ρ^2 W^2 + ...` contains non-zero off-diagonal elements and diagonal elements strictly exceeding `1`, an incremental change in covariate `x_ik` in region `i` not only affects outcome `y_i` directly, but also diffuses to neighboring region `j` (`i -> j`), which in turn feeds back onto region `i` (`j -> i`). To correctly quantify these mechanisms, LeSage & Pace (2009) established three scalar summary measures: the Average Direct Impact (`(1 / N) tr(S_k(W))`, capturing the average within-region effect including circular feedback), the Average Total Impact (`(1 / N) 1_N' S_k(W) 1_N`, which simplifies to `(β_k + θ_k) / (1 - ρ)` for row-standardized weights without islands), and the Average Indirect Impact (calculated as Total minus Direct, measuring cross-border spillovers). In R `spatialreg` `v1.4-3`, researchers compute these quantities alongside Monte Carlo simulated z-values using `impacts(sdm_fit, tr = trW(as(lw, "CsparseMatrix"), type = "mult"), R = 1000)`.
Reproducible Spatial Econometric Pipelines in HumanPen Start Project
Translating raw vector shapefiles, regional census microdata, and spatial econometric theory into journal-ready empirical manuscripts requires coordinating projection transformations, spatial weights matrix construction, Lagrange Multiplier diagnostics, and LeSage-Pace impact decomposition. In HumanPen Start Project, researchers execute this pipeline reproducibly end-to-end. Attach your data and papers, describe what you need, approve the plan before work starts, and get the reviewed report, charts, and code ready to preview online or download.
The platform operates under strict technical parameters designed for rigorous quantitative workflows: project uploads support Excel, CSV, Word, PDF, and zip archives up to 5 GB total per project. Analysis pipelines execute in an isolated CPU-based Python or R sandbox environment. If preliminary analyses were drafted in commercial legacy packages like Stata or SPSS, our engineering workflows convert them into reproducible open-source GeoPandas, PySAL, sf, and spdep scripts with fully verified standard errors. Restricted commercial databases (such as WRDS, Wind, or proprietary municipal boundary datasets) must be exported by the researcher under their institutional data agreement prior to upload. GPU model training is not supported. All project assets are encrypted in transit, isolated on a per-project basis, and never utilized for machine learning model training. Files are retained for 6 months after the last user activity, with an automated email reminder 3 days prior to expiration, and can be permanently deleted by the user at any point.
For complex empirical investigations that combine spatial econometric models with panel identification strategies, researchers can cross-reference our public microdata empirical workflow for multi-source microdata merging and our staggered difference-in-differences panel workflow to pair spatial lag processes with dynamic causal event studies. Integrating spatial weights and impact matrices directly into structured LaTeX tables eliminates manual copy-paste errors and ensures complete computational reproducibility across empirical revisions.
Empirical code, Moran's I diagnostics, spatial regression tables, and impact summaries produced in Start Project serve strictly as reproducible methodological and learning reference scaffolds; researchers must independently verify econometric assumptions, review raw estimation logs, and uphold their academic institution's data governance standards.
Frequently Asked Questions About Spatial Econometrics in Python and R
How should I choose between Queen and Rook contiguity weights matrices? Queen contiguity is the standard default for polygonal administrative units because it defines neighbors as any two units sharing either a common boundary edge or a corner vertex point, preventing artificial disconnections caused by digitization imperfections at four-corner intersections. Rook contiguity requires a shared linear boundary of length strictly greater than zero and should only be selected when economic or geographic theory dictates that interactions cannot occur across diagonal corner points, such as agricultural water-basin sharing or contiguous railway rights-of-way.
What should I do when my study area includes islands or disconnected administrative units? When your shapefile includes islands or remote enclaves with zero contiguity neighbors, `spdep` functions in R halt execution with an error by default. You can resolve this either by passing `zero.policy = TRUE` consistently across `nb2listw()`, `moran.test()`, `lagsarlm()`, and `impacts()`, or by replacing contiguity weights with a `k`-nearest neighbors specification (`KNN.from_dataframe(gdf, k=6)` in Python or `knn2nb(knearneigh(coords, k = 6))` in R). Because `k >= 1` guarantees that every observation has exactly `k` neighbors, island errors are eliminated, though researchers using asymmetric `k-NN` weights must use sparse matrix algorithms or enforce symmetry via `make.sym.nb()` when Cholesky decomposition is required.
Why did spdep replace lm.LMtests with lm.RStests in recent versions? In `spdep` versions `v1.3-2` through `v1.4-3`, the legacy function `lm.LMtests()` was superseded by `spdep::lm.RStests(ols_fit, listw, test = "all")` to reflect modern mathematical statistics terminology, which recognizes these Lagrange Multiplier tests as Rao's Score tests tracing back to C.R. Rao (1948). The updated function computes the exact same underlying statistics—`RSerr`, `RSlag`, robust `adjRSerr`, robust `adjRSlag`, and portmanteau `SARMA`—while aligning function naming with contemporary asymptotic econometrics literature.
How does HumanPen safeguard proprietary spatial boundaries and confidential regional datasets? All project files uploaded to HumanPen are encrypted in transit and processed within isolated, dedicated CPU sandbox environments. Research datasets are never shared across user accounts and are never utilized to train AI models. Uploaded materials are securely stored for 6 months after the last project activity, accompanied by a reminder notification 3 days before expiration, and can be permanently removed from disk at any time via the project management dashboard.
Sources
- GeoPandas Documentation — Coordinate Reference Systems User Guide — Technical guide on managing geographic vs projected coordinate systems and avoiding planar distortion in vector geometries.
- PySAL libpysal Queen Spatial Weights Reference — Specification and API documentation for constructing Queen contiguity spatial weights matrices from GeoDataFrames.
- PySAL libpysal k-Nearest Neighbors Spatial Weights Reference — Reference documentation for building island-free k-NN spatial weights matrices.
- PySAL esda Global Moran's I Spatial Autocorrelation Reference — Official documentation for global spatial autocorrelation testing and analytical p-value calculations.
- PySAL esda Local Moran's I (LISA) Reference — Technical reference for Anselin's local indicators of spatial association and false discovery rate cluster filtering.
- Edzer Pebesma & Dewey Dunnington — Spherical geometry in sf using s2geometry — Comprehensive vignette on spherical coordinate geometry, planar projections, and distance calculations in R.
- CRAN Package spdep — lm.RStests Rao's Score Diagnostics — Reference manual for Anselin et al. (1996) Rao's score and Lagrange multiplier spatial dependence diagnostics in linear regression.
- CRAN Package spatialreg — impacts in Spatial Lag and Durbin Models — Documentation for computing LeSage & Pace (2009) average direct, indirect, and total impacts via sparse matrix trace approximations.
- LeSage & Pace (2009) — Introduction to Spatial Econometrics — Foundational textbook formulating the spatial multiplier matrix, spatial Durbin model specifications, and scalar impact interpretation.
- Anselin, Bera, Florax & Yoon (1996) — Simple diagnostic tests for spatial dependence — Seminal paper establishing Lagrange multiplier / Rao's score test statistics and robust diagnostics for spatial lag and spatial error models.
KEEP READING