Skip to content

CSpatial · spatial.regression

Spatial regression (LM tests, spatial lag and spatial error models)

Does an ordinary regression miss spatial dependence, and does a spatial lag or spatial error model fit better?

Lagrange multiplier tests show whether ordinary regression leaves spatial dependence behind and suggest which kind. The spatial lag model lets an outcome depend on neighbors' outcomes, with direct and spillover impacts. The spatial error model lets unmeasured influences be shared between neighbors. Both are fitted by maximum likelihood.

Verified in Python and R Python and R agree to 6 decimals Also called spatial lag model, SAR, spatial autoregressive model…

A real result

Example “Columbus lm tests”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Ordinary regression with LM testsRecorded · Python and R agreeRecorded 2026-11-25 · 42 values compared
R

LM error = 5.21, p = .023; LM lag = 8.90, p = .003

Squared correlation of fit
0.5524
AIC
382.75
Moran's I of residuals
0.2221
p of residual Moran's I
.008

Plots

Residuals against their neighborsDo sites resemble their neighbors, and which sites break the pattern?
View data
SiteResidual (standardized)Average of neighbors (spatial lag)
10.0313−0.4054
2−0.3335−0.7499
3−0.4772−0.3810
4−1.804−0.1004
50.5819−0.1881
6−0.81900.4894
7−3.1060.6444
8−0.1728−0.3402
90.39680.1027
101.219−0.1047
110.99100.3310
120.8654−0.0138
130.4308−0.2399
141.4540.1380
150.06030.4106
160.32030.8431
17−0.42090.4603
181.1590.8912
191.1591.081
200.31540.1139
21−0.54640.6819
22−0.71030.4534
23−0.1538−0.2812
240.63101.003
251.0020.6441
26−0.82800.4558
270.9750−0.0363
280.64160.3586
291.3450.8587
302.5860.7185
31−1.369−1.100
32−0.73810.2556
33−0.39210.4474
34−1.171−0.7744
35−0.14260.2273
36−1.303−0.6847
371.1620.7033
380.81700.3515
39−0.8265−0.9502
401.105−0.1418
41−0.24460.1559
420.1213−1.237
43−0.3198−0.1689
44−0.5766−0.3264
45−0.8498−0.2862
46−0.1781−1.065
470.10060.4303
48−1.423−0.5775
49−0.5639−0.9497

Assumptions

  • Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). The neighbors are part of the model; try a second definition as a sensitivity check.
  • Normal residuals — Shapiro–Wilk on the residuals: p = .450.
  • Equal variance across sites — Regions of very different sizes often have unequal variance; rates from small regions are noisier.
  • Spillover is not proof of a mechanism — A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.

Coefficients

TermEstimateSEEstimate/SEp
(Intercept)68.6194.73514.490< .001
income−1.5970.3341−4.780< .001
housing−0.27390.1032−2.654.008

Lagrange multiplier tests on the ordinary regression

Testχ²dfp
LM error5.2061.023
Robust LM error0.04391.834
LM lag8.8981.003
Robust LM lag3.7361.053
SARMA (both)8.9422.011
  • Neighbors: Queen contiguity, row-standardized (W).
Python

LM error = 5.21, p = .023; LM lag = 8.90, p = .003

Squared correlation of fit
0.5524
AIC
382.75
Moran's I of residuals
0.2221
p of residual Moran's I
.008

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). The neighbors are part of the model; try a second definition as a sensitivity check.
  • Normal residuals — Shapiro–Wilk on the residuals: p = .450.
  • Equal variance across sites — Regions of very different sizes often have unequal variance; rates from small regions are noisier.
  • Spillover is not proof of a mechanism — A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.

Coefficients

TermEstimateSEEstimate/SEp
(Intercept)68.6194.73514.490< .001
income−1.5970.3341−4.780< .001
housing−0.27390.1032−2.654.008

Lagrange multiplier tests on the ordinary regression

Testχ²dfp
LM error5.2061.023
Robust LM error0.04391.834
LM lag8.8981.003
Robust LM lag3.7361.053
SARMA (both)8.9422.011
  • Neighbors: Queen contiguity, row-standardized (W).

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Columbus lm testssp_columbus · region: site · x_variables: income, housing · y: crime
  • Columbus lagsp_columbus · region: site · x_variables: income, housing · y: crime
  • Columbus errorsp_columbus · region: site · x_variables: income, housing · y: crime
  • Nc lag knnsp_nc_sids · lat: lat · lon: lon · x_variables: births79 · y: rate
  • Degenerate constantsp_columbus · region: site · x_variables: income, housing · y: crime
  • Degenerate n3sp_columbus · region: site · x_variables: income, housing · y: crime

In the guides

Where it sits in the decision guides

  • Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association

What you need

Outcomenumeric · 1 column
What you want to explain at each site.
Predictorsnumeric / boolean · 1–30 columns
Numeric predictors at each site; encode categories in Prepare first.
Regioncategorical / numeric · 0–1 column
One row per region, with the map layer's feature id (FIPS code, ISO code …). Needs a map layer.
Longitudenumeric · 0–1 column
Degrees east, when sites are points instead of regions of a map layer.
Latitudenumeric · 0–1 column
Degrees north, when sites are points instead of regions of a map layer.

Choices you make

options

Modeldefault lm_tests

Which model to fit. The LM tests suggest whether a lag or an error model suits the data.

  • Ordinary regression with LM tests(default) — Start here: fits ordinary regression and tests which spatial model its residuals point to.
  • Spatial lag — Each site's outcome depends on its neighbors' outcomes, so effects spill over.
  • Spatial error — Unmeasured influences are shared between neighbors; coefficients keep their usual meaning.
Map layerdefault —

Regions to build neighbors from; rows match features through the Region role. Leave empty to use longitude and latitude columns.

Neighborsdefault queen

Which sites count as neighbors. The host builds the weights once; Python and R read the same file.

  • Queen contiguity(default) — Regions sharing any boundary point.
  • Rook contiguity — Regions sharing a boundary edge (two or more points).
  • k nearest — Each site's k closest sites (not symmetric).
  • Distance band — All sites within a distance.
  • Inverse distance — Closer sites weigh more: 1 / distance^power.
  • Kernel — Weights fall smoothly to zero at a bandwidth.
Neighbors (k)default 4

How many nearest sites count as neighbors (k nearest), or set the adaptive kernel bandwidth.

Distance (km)default —

Distance band, inverse-distance cut-off or fixed kernel bandwidth, in km between longitude/latitude sites.

Distance powerdefault 1

Inverse-distance decay: 1 = 1/d, 2 = 1/d².

Kerneldefault triangular

Shape of the decay inside the bandwidth.

  • Triangular(default) — 1 − d/h.
  • Uniform — Equal weight inside the bandwidth.
  • Quadratic (Epanechnikov) — ¾ (1 − (d/h)²).
  • Quartic (biweight) — 15/16 (1 − (d/h)²)².
  • Gaussian — Normal density of d/h, cut at the bandwidth.
Adaptive bandwidthdefault off

Each site's bandwidth reaches its k-th nearest site, so dense areas get narrower kernels.

Weights styledefault W

How weights are scaled (spdep styles). Row-standardized is the usual choice for Moran's I and spatial lags.

  • Row-standardized (W)(default) — Each site's weights sum to 1: spatial lags are neighbor averages.
  • Binary (B) — 1 for neighbors (raw weights for inverse distance and kernels).
  • Global (C) — All weights sum to the number of sites.
  • Sum to one (U) — All weights together sum to 1.
  • Variance-stabilizing (S) — Tiefelsdorf's style: between W and C for uneven neighbor counts.
  • Min–max — Divided by the smaller of the largest row and column sums.
Sites with no neighborsdefault keep

Islands (e.g. Hawaii with contiguity) have no neighbors; keep them, stop, or join each to its nearest site.

  • Keep (no neighbors)(default) — Tests exclude or zero their lag (spdep zero.policy).
  • Stop and list them — Fail so you can choose a different neighborhood.
  • Join to the nearest site — Add a link to the closest site in both directions.

hypothesis

Significance leveldefault 0.05

Level used in the narrative.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Neighbors chosen for a reason

    The neighbor rule is part of the model; report it and try a second definition.

  • Normal residuals

    The likelihood assumes normal errors; LM tests and standard errors are approximate otherwise.

  • Equal variance across sites

    Regions of very different sizes often have unequal variance; rates from small regions are noisier.

  • Spillover is not proof of a mechanism

    A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.

What it reports

  • Tests: No spatial dependence in the model
n
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
coef
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
coef_se
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
coef_z
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
coef_p
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
lower
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
upper
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
sigma2
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
ll
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
aic
A model score balancing fit against complexity; lower is better, and only differences matter.
ll_ols
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
aic_ols
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
lr
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
lr_p
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
lm_error
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
lm_error_p
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
lm_lag
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
lm_lag_p
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
rlm_error
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
rlm_error_p
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
rlm_lag
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
rlm_lag_p
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
sarma
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
sarma_p
Tests on ordinary regression residuals that say whether a spatial lag or a spatial error model is called for.
residual_moran
Unmeasured influences are shared between neighbors through λ; coefficients keep their usual meaning.
residual_moran_p
Unmeasured influences are shared between neighbors through λ; coefficients keep their usual meaning.
pseudo_r2
Unmeasured influences are shared between neighbors through λ; coefficients keep their usual meaning.
islands
Sites with no neighbors under the chosen rule, such as Hawaii with contiguity.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.
apa_text
The spatial parameter, its standard error, p-value and AIC in APA style, as the summary quotes them.
model_label
Which spatial regression was fitted: the spatial lag model, the spatial error model or plain OLS.
verdict
One sentence on what the spatial parameter says about how neighbors influence each other.

Per group, level or term: beta[<term>], se[<term>], p[<term>], direct[<term>], indirect[<term>], total[<term>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, jsonlite, codesplashr.

Default traps between the two languages

  • With no spatial process at 80 sites the error model's tests run a little high: 6.6% for the likelihood ratio and 7.6% for coefficients at the 5% level over 2,000 maps. They use the same asymptotic references as spatialreg. At 300 sites both are 4.8% (1,000 maps). The card notes this below 200 sites.
  • Both engines maximize the same concentrated likelihood by the same golden-section search over the eigenvalue range. LM tests match spdep::lm.RStests to 1e-9. Coefficients, log-likelihoods and impacts match spatialreg's eigen method to about 1e-5, its optimizer's own tolerance; standard errors come from the analytic information matrix and match to about 1e-3.
Python

The exact script CodeSplash ran for example “Columbus lm tests” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Spatial regression (LM tests, spatial lag and spatial error models)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.regression 1.1.1 · spec f3d0ddda141a0264
# Dataset: sp_columbus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import spatial as sp
from codesplash.stats import spatial_reg as spr
from codesplash.stats import spatial_weights as sw

# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_columbus.parquet", columns=["crime", "income", "housing", "site"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=sorted(df["site"].dropna().unique()))
df = df.dropna(subset=["crime", "income", "housing", "site"])  # listwise deletion over the analysis columns
df["site"] = df["site"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["crime", "income", "housing", "site"])  # infinite values stop the run (registry/errors.yaml)

# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so Python
# and R read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt = sw.load_weights("target/academy-parity/run-8142/spatial.regression/columbus-lm-tests/out-python")
if len(df) != wt["n"]:
    wt = sw.weights_subset(wt, df.index.to_numpy())
n_islands = len(wt["islands"])
neighbours_label = wt["description"] or "the chosen neighbors"
if n_islands:
    warnings.append(f"{n_islands} site(s) have no neighbors; their spatial lag is 0 and local tests skip them.")
site = df["site"].astype(str).to_numpy()

# %% Model
# Lagrange multiplier tests (Anselin 1988; Anselin et al. 1996) and spatial lag or error models by maximum
# likelihood (Ord 1975), with direct and indirect impacts (LeSage & Pace 2009).
Y = "crime"
X_VARS = ["income", "housing"]
model = "lm_tests"  # lm_tests | lag | error
alpha = 0.05
y = df[Y].to_numpy(dtype=float)
X = df[X_VARS].astype(float).to_numpy()
n = y.size
# Inputs the model can't fit stop with a catalog message (registry/errors.yaml), the same in R: more sites than
# coefficients, and an outcome and predictors that vary.
cs.check_rows(n, len(X_VARS) + 2, "The spatial regression")
check_not_constant(y, Y)
for v in X_VARS:
    check_not_constant(df[v], v)
if n_islands:
    raise ValueError(f"{n_islands} site(s) have no neighbors. Spatial regression needs every site linked: join islands to their nearest site.")
ols = spr.lm_tests(wt, y, X, X_VARS)
terms = ols["terms"]
fit = None
if model == "lag":
    fit = spr.lag_model(wt, y, X, X_VARS)
elif model == "error":
    fit = spr.error_model(wt, y, X, X_VARS)
use = fit if fit else ols
beta, se, residuals = use["beta"], use["se"], use["residuals"]
z_terms = beta / se
p_terms = 2.0 * stats.norm.sf(np.abs(z_terms))
moran = sp.global_test(wt, residuals, "moran", "randomization", "two_sided")
yhat = y - residuals
pseudo_r2 = float(np.corrcoef(y, yhat)[0, 1] ** 2)

# %% Assumptions
shapiro_p = float(stats.shapiro(residuals)[1]) if 3 <= n <= 5000 else None
assumptions = [
    {"key": "weights_chosen", "label": "Neighbors chosen for a reason", "status": "info",
     "detail": f"Neighbors: {neighbours_label}. The neighbors are part of the model; try a second definition as a sensitivity check."},
    {"key": "residual_normal", "label": "Normal residuals", "status": "info" if shapiro_p is None else ("pass" if shapiro_p >= 0.05 else "warn"),
     "detail": "Shapiro–Wilk not run for this many sites." if shapiro_p is None else f"Shapiro–Wilk on the residuals: {cs.fmt_p(shapiro_p)}."},
    {"key": "equal_variance", "label": "Equal variance across sites", "status": "info",
     "detail": "Regions of very different sizes often have unequal variance; rates from small regions are noisier."},
    {"key": "causal", "label": "Spillover is not proof of a mechanism", "status": "info",
     "detail": "A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread."},
]

# %% Result
t, tp = ols["tests"], ols["p"]
values = {"n": n, "k": len(terms), "sigma2": use["sigma2"], "ll": use["ll"], "aic": use["aic"], "ll_ols": ols["ll"], "aic_ols": ols["aic"],
          "lm_error": t["lm_error"], "lm_error_p": tp["lm_error"], "lm_lag": t["lm_lag"], "lm_lag_p": tp["lm_lag"],
          "rlm_error": t["rlm_error"], "rlm_error_p": tp["rlm_error"], "rlm_lag": t["rlm_lag"], "rlm_lag_p": tp["rlm_lag"],
          "sarma": t["sarma"], "sarma_p": tp["sarma"], "residual_moran": moran["statistic"], "residual_moran_p": moran["p"],
          "pseudo_r2": pseudo_r2, "islands": n_islands, "missing_share": n_dropped / n_input if n_input else 0.0}
for k, term in enumerate(terms):
    values[f"beta[{term}]"] = float(beta[k])
    values[f"se[{term}]"] = float(se[k])
    values[f"p[{term}]"] = float(p_terms[k])
tables = [{"key": "coefficients", "title": "Coefficients", "columns": [
    {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
    {"key": "z", "label": "z" if fit else "Estimate/SE", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
    "rows": [{"term": terms[k], "estimate": float(beta[k]), "se": float(se[k]), "z": float(z_terms[k]), "p": float(p_terms[k])} for k in range(len(terms))]}]
tables.append({"key": "lm", "title": "Lagrange multiplier tests on the ordinary regression", "columns": [
    {"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "χ²", "type": "number"}, {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}],
    "rows": [{"test": label, "statistic": t[key], "df": 2 if key == "sarma" else 1, "p": tp[key]}
             for key, label in (("lm_error", "LM error"), ("rlm_error", "Robust LM error"), ("lm_lag", "LM lag"), ("rlm_lag", "Robust LM lag"), ("sarma", "SARMA (both)"))]})
statistics = [{"key": "pseudo_r2", "label": "Squared correlation of fit", "value": pseudo_r2}, {"key": "aic", "label": "AIC", "value": use["aic"]},
              {"key": "residual_moran", "label": "Moran's I of residuals", "value": moran["statistic"]},
              {"key": "residual_moran_p", "label": "p of residual Moran's I", "value": moran["p"], "format": "p"}]
if fit:
    symbol = "ρ" if model == "lag" else "λ"
    coef, coef_se = fit["coef"], fit["coef_se"]
    coef_z, coef_p = spr.wald(coef, coef_se)
    lower, upper = coef - stats.norm.ppf(0.975) * coef_se, coef + stats.norm.ppf(0.975) * coef_se
    lr = 2.0 * (fit["ll"] - ols["ll"])
    lr_p = float(stats.chi2.sf(lr, 1))
    values.update({"coef": coef, "coef_se": coef_se, "coef_z": coef_z, "coef_p": coef_p, "lower": lower, "upper": upper, "lr": lr, "lr_p": lr_p})
    statistics = [{"key": "coef", "label": symbol, "value": coef}, {"key": "coef_se", "label": f"SE of {symbol}", "value": coef_se}, {"key": "coef_p", "label": "p", "value": coef_p, "format": "p"},
                  {"key": "lr", "label": "LR against ordinary regression", "value": lr}] + statistics
    model_label = "Spatial lag model" if model == "lag" else "Spatial error model"
    what = "outcomes depend on neighboring outcomes" if model == "lag" else "unmeasured influences are shared between neighbors"
    verdict = (f"{symbol} = {coef:.3f} (SE {coef_se:.3f}), {cs.fmt_p(coef_p)}: " + (f"the data support a model where {what}." if coef_p < alpha else f"no clear evidence that {what}.")
               + f" Moran's I of the residuals is {moran['statistic']:.3f}, {cs.fmt_p(moran['p'])}.")
    apa_text = f"{symbol} = {coef:.2f}, SE = {coef_se:.2f}, {cs.fmt_p(coef_p)}, AIC = {fit['aic']:.1f}"
    if model == "lag":
        for k, term in enumerate(X_VARS):
            values[f"direct[{term}]"] = float(fit["direct"][k])
            values[f"indirect[{term}]"] = float(fit["indirect"][k])
            values[f"total[{term}]"] = float(fit["total"][k])
        tables.append({"key": "impacts", "title": "Average impacts: effect at the site, spillover to others, and both", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "direct", "label": "Direct", "type": "number"}, {"key": "indirect", "label": "Indirect", "type": "number"}, {"key": "total", "label": "Total", "type": "number"}],
            "rows": [{"term": term, "direct": float(fit["direct"][k]), "indirect": float(fit["indirect"][k]), "total": float(fit["total"][k])} for k, term in enumerate(X_VARS)]})
else:
    model_label = "Ordinary regression with LM tests"
    err, lag = tp["rlm_error"] < alpha, tp["rlm_lag"] < alpha
    if tp["lm_error"] >= alpha and tp["lm_lag"] >= alpha:
        verdict = "Neither LM test finds spatial dependence in the residuals; ordinary regression looks adequate for these neighbors."
    elif err and not lag:
        verdict = "The robust tests point to a spatial error model."
    elif lag and not err:
        verdict = "The robust tests point to a spatial lag model."
    elif err and lag:
        verdict = "Both robust tests are significant; compare the lag and error models by fit."
    else:
        verdict = "An LM test finds spatial dependence, but the robust tests do not separate lag from error; compare both models."
    apa_text = f"LM error = {t['lm_error']:.2f}, {cs.fmt_p(tp['lm_error'])}; LM lag = {t['lm_lag']:.2f}, {cs.fmt_p(tp['lm_lag'])}"
values.update({"model_label": model_label, "verdict": verdict, "apa_text": apa_text})
summary = f"{model_label} of {Y} on {', '.join(X_VARS)} ({n} sites). {verdict}"
charts = [cs.chart("residuals", "moran-scatter", "Residuals against their neighbors", {
    "x": cs.col("Residual (standardized)", (residuals - residuals.mean()) / residuals.std(ddof=0)),
    "y": cs.col("Average of neighbors (spatial lag)", sw.weights_lag(wt, (residuals - residuals.mean()) / residuals.std(ddof=0))),
    "site": cs.col("Site", site)}, controls={"slope": moran["statistic"]})]
for key in ["coef", "coef_se", "coef_z", "coef_p", "lower", "upper", "lr", "lr_p"]:  # only some options produce these
    values.setdefault(key, None)
cs.publish({
    "method": "spatial.regression",
    "methodVersion": "1.1.1",
    "title": model_label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": apa_text,
    "statistics": statistics,
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Neighbors: {neighbours_label}."] + (["With no spatial process at 80 sites this model's tests rejected 6.6% (likelihood ratio) and 7.6% (coefficients) at the 5% level in simulation, and 4.8% at 300 sites. They are asymptotic: read p-values near .05 cautiously below 200 sites."] if model == "error" and n < 200 else []),
    "values": values,
    "charts": charts,
})
R

The exact script CodeSplash ran for example “Columbus lm tests” · R version 4.5.1 (2025-06-13)

# Spatial regression (LM tests, spatial lag and spatial error models)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.regression 1.1.1 · spec f3d0ddda141a0264
# Dataset: sp_columbus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_columbus.parquet", col_select = c("crime", "income", "housing", "site")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = sort(unique(df[["site"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("crime", "income", "housing", "site")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("crime", "income", "housing", "site"))  # infinite values stop the run (registry/errors.yaml)

# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so R and
# Python read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt <- cs_load_weights("target/academy-parity/run-8142/spatial.regression/columbus-lm-tests/out-r")
if (nrow(df) != wt$n) wt <- cs_weights_subset(wt, as.integer(rownames(df)))
n_islands <- length(wt$islands)
neighbours_label <- if (nzchar(wt$description)) wt$description else "the chosen neighbors"
if (n_islands > 0) {
  warnings <- c(warnings, sprintf("%d site(s) have no neighbors; their spatial lag is 0 and local tests skip them.", n_islands))
}
site <- as.character(df[["site"]])

# %% Model
# Lagrange multiplier tests (Anselin 1988; Anselin et al. 1996) and spatial lag or error models by maximum
# likelihood (Ord 1975), with direct and indirect impacts (LeSage & Pace 2009).
Y <- "crime"
X_VARS <- c("income", "housing")
model <- "lm_tests"  # lm_tests | lag | error
alpha <- 0.05
y <- as.numeric(df[[Y]])
X <- vapply(X_VARS, function(v) as.numeric(df[[v]]), numeric(nrow(df)))
if (is.null(dim(X))) X <- matrix(X, nrow = nrow(df))
n <- length(y)
# Inputs the model can't fit stop with a catalog message (registry/errors.yaml), the same in Python: more sites
# than coefficients, and an outcome and predictors that vary.
cs_check_rows(n, length(X_VARS) + 2, "The spatial regression")
cs_check_not_constant(y, Y)
for (v in X_VARS) cs_check_not_constant(df[[v]], v)
if (n_islands > 0) stop(sprintf("%d site(s) have no neighbors. Spatial regression needs every site linked: join islands to their nearest site.", n_islands))
ols <- cs_spr_lm_tests(wt, y, X, X_VARS)
terms <- ols$terms
fit <- NULL
if (model == "lag") fit <- cs_spr_lag_model(wt, y, X, X_VARS)
if (model == "error") fit <- cs_spr_error_model(wt, y, X, X_VARS)
use <- if (!is.null(fit)) fit else ols
beta <- use$beta
se <- use$se
residuals <- use$residuals
z_terms <- beta / se
p_terms <- 2 * stats::pnorm(abs(z_terms), lower.tail = FALSE)
moran <- cs_sp_global_test(wt, residuals, "moran", "randomization", "two_sided")
yhat <- y - residuals
pseudo_r2 <- stats::cor(y, yhat)^2

# %% Assumptions
shapiro_p <- if (n >= 3 && n <= 5000) stats::shapiro.test(residuals)$p.value else NULL
assumptions <- list(
  list(key = "weights_chosen", label = "Neighbors chosen for a reason", status = "info",
       detail = sprintf("Neighbors: %s. The neighbors are part of the model; try a second definition as a sensitivity check.", neighbours_label)),
  list(key = "residual_normal", label = "Normal residuals", status = if (is.null(shapiro_p)) "info" else if (shapiro_p >= 0.05) "pass" else "warn",
       detail = if (is.null(shapiro_p)) "Shapiro–Wilk not run for this many sites." else sprintf("Shapiro–Wilk on the residuals: %s.", cs_fmt_p(shapiro_p))),
  list(key = "equal_variance", label = "Equal variance across sites", status = "info",
       detail = "Regions of very different sizes often have unequal variance; rates from small regions are noisier."),
  list(key = "causal", label = "Spillover is not proof of a mechanism", status = "info",
       detail = "A significant lag coefficient can come from omitted variables with a spatial pattern; it does not prove spread.")
)

# %% Result
t_ <- ols$tests
tp <- ols$p
values <- list(n = n, k = length(terms), sigma2 = use$sigma2, ll = use$ll, aic = use$aic, ll_ols = ols$ll, aic_ols = ols$aic,
               lm_error = t_$lm_error, lm_error_p = tp$lm_error, lm_lag = t_$lm_lag, lm_lag_p = tp$lm_lag,
               rlm_error = t_$rlm_error, rlm_error_p = tp$rlm_error, rlm_lag = t_$rlm_lag, rlm_lag_p = tp$rlm_lag,
               sarma = t_$sarma, sarma_p = tp$sarma, residual_moran = moran$statistic, residual_moran_p = moran$p,
               pseudo_r2 = pseudo_r2, islands = n_islands, missing_share = if (n_input > 0) n_dropped / n_input else 0)
for (k in seq_along(terms)) {
  values[[sprintf("beta[%s]", terms[k])]] <- beta[k]
  values[[sprintf("se[%s]", terms[k])]] <- se[k]
  values[[sprintf("p[%s]", terms[k])]] <- p_terms[k]
}
tables <- list(list(key = "coefficients", title = "Coefficients", columns = list(
  list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"), list(key = "se", label = "SE", type = "number"),
  list(key = "z", label = if (!is.null(fit)) "z" else "Estimate/SE", type = "number"), list(key = "p", label = "p", type = "pvalue")),
  rows = lapply(seq_along(terms), function(k) list(term = terms[k], estimate = beta[k], se = se[k], z = z_terms[k], p = p_terms[k]))))
lm_keys <- c("lm_error", "rlm_error", "lm_lag", "rlm_lag", "sarma")
lm_labels <- c("LM error", "Robust LM error", "LM lag", "Robust LM lag", "SARMA (both)")
tables[[2]] <- list(key = "lm", title = "Lagrange multiplier tests on the ordinary regression", columns = list(
  list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "χ²", type = "number"), list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")),
  rows = lapply(seq_along(lm_keys), function(i) list(test = lm_labels[i], statistic = t_[[lm_keys[i]]], df = if (lm_keys[i] == "sarma") 2L else 1L, p = tp[[lm_keys[i]]])))
statistics <- list(list(key = "pseudo_r2", label = "Squared correlation of fit", value = pseudo_r2), list(key = "aic", label = "AIC", value = use$aic),
                   list(key = "residual_moran", label = "Moran's I of residuals", value = moran$statistic),
                   list(key = "residual_moran_p", label = "p of residual Moran's I", value = moran$p, format = "p"))
if (!is.null(fit)) {
  symbol <- if (model == "lag") "ρ" else "λ"
  coef <- fit$coef
  coef_se <- fit$coef_se
  wald <- cs_spr_wald(coef, coef_se)
  coef_z <- wald[1]
  coef_p <- wald[2]
  lower <- coef - stats::qnorm(0.975) * coef_se
  upper <- coef + stats::qnorm(0.975) * coef_se
  lr <- 2 * (fit$ll - ols$ll)
  lr_p <- stats::pchisq(lr, 1, lower.tail = FALSE)
  values <- c(values, list(coef = coef, coef_se = coef_se, coef_z = coef_z, coef_p = coef_p, lower = lower, upper = upper, lr = lr, lr_p = lr_p))
  statistics <- c(list(list(key = "coef", label = symbol, value = coef), list(key = "coef_se", label = sprintf("SE of %s", symbol), value = coef_se),
                       list(key = "coef_p", label = "p", value = coef_p, format = "p"), list(key = "lr", label = "LR against ordinary regression", value = lr)), statistics)
  model_label <- if (model == "lag") "Spatial lag model" else "Spatial error model"
  what <- if (model == "lag") "outcomes depend on neighboring outcomes" else "unmeasured influences are shared between neighbors"
  verdict <- paste0(sprintf("%s = %.3f (SE %.3f), %s: ", symbol, coef, coef_se, cs_fmt_p(coef_p)),
                    if (coef_p < alpha) sprintf("the data support a model where %s.", what) else sprintf("no clear evidence that %s.", what),
                    sprintf(" Moran's I of the residuals is %.3f, %s.", moran$statistic, cs_fmt_p(moran$p)))
  apa_text <- sprintf("%s = %.2f, SE = %.2f, %s, AIC = %.1f", symbol, coef, coef_se, cs_fmt_p(coef_p), fit$aic)
  if (model == "lag") {
    for (k in seq_along(X_VARS)) {
      values[[sprintf("direct[%s]", X_VARS[k])]] <- fit$direct[k]
      values[[sprintf("indirect[%s]", X_VARS[k])]] <- fit$indirect[k]
      values[[sprintf("total[%s]", X_VARS[k])]] <- fit$total[k]
    }
    tables[[3]] <- list(key = "impacts", title = "Average impacts: effect at the site, spillover to others, and both", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "direct", label = "Direct", type = "number"), list(key = "indirect", label = "Indirect", type = "number"), list(key = "total", label = "Total", type = "number")),
      rows = lapply(seq_along(X_VARS), function(k) list(term = X_VARS[k], direct = fit$direct[k], indirect = fit$indirect[k], total = fit$total[k])))
  }
} else {
  model_label <- "Ordinary regression with LM tests"
  err <- tp$rlm_error < alpha
  lag <- tp$rlm_lag < alpha
  verdict <- if (tp$lm_error >= alpha && tp$lm_lag >= alpha) {
    "Neither LM test finds spatial dependence in the residuals; ordinary regression looks adequate for these neighbors."
  } else if (err && !lag) {
    "The robust tests point to a spatial error model."
  } else if (lag && !err) {
    "The robust tests point to a spatial lag model."
  } else if (err && lag) {
    "Both robust tests are significant; compare the lag and error models by fit."
  } else {
    "An LM test finds spatial dependence, but the robust tests do not separate lag from error; compare both models."
  }
  apa_text <- sprintf("LM error = %.2f, %s; LM lag = %.2f, %s", t_$lm_error, cs_fmt_p(tp$lm_error), t_$lm_lag, cs_fmt_p(tp$lm_lag))
}
values <- c(values, list(model_label = model_label, verdict = verdict, apa_text = apa_text))
summary <- sprintf("%s of %s on %s (%d sites). %s", model_label, Y, paste(X_VARS, collapse = ", "), n, verdict)
zr <- (residuals - mean(residuals)) / sqrt(mean((residuals - mean(residuals))^2))
charts <- list(cs_chart("residuals", "moran-scatter", "Residuals against their neighbors", list(
  x = cs_col("Residual (standardized)", zr), y = cs_col("Average of neighbors (spatial lag)", cs_weights_lag(wt, zr)),
  site = cs_col("Site", site)), controls = list(slope = moran$statistic)))
for (key in c("coef", "coef_se", "coef_z", "coef_p", "lower", "upper", "lr", "lr_p")) if (is.null(values[[key]])) values[[key]] <- NA_real_  # only some options produce these
cs_publish(list(
  method = "spatial.regression",
  methodVersion = "1.1.1",
  title = model_label,
  engine = cs_engine_info("stats"),
  n = n,
  summary = summary,
  apa = apa_text,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = c(list(sprintf("Neighbors: %s.", neighbours_label)), if (model == "error" && n < 200) list("With no spatial process at 80 sites this model's tests rejected 6.6% (likelihood ratio) and 7.6% (coefficients) at the 5% level in simulation, and 4.8% at 300 sites. They are asymptotic: read p-values near .05 cautiously below 200 sites.")),
  values = values,
  charts = charts
))

Sources

  • Anselin, L. (1988). Spatial Econometrics: Methods and Models. Kluwer.
  • Anselin, L., Bera, A. K., Florax, R., & Yoon, M. J. (1996). Simple diagnostic tests for spatial dependence. Regional Science and Urban Economics, 26, 77–104.
  • Ord, K. (1975). Estimation methods for models of spatial interaction. JASA, 70, 120–126.
  • LeSage, J., & Pace, R. K. (2009). Introduction to Spatial Econometrics. CRC Press.

From the CodeSplash method registry · spatial.regression v1.1.1.