CSpatial · spatial.autocorrelation
Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts)
Do similar values sit closer together on the map than chance alone would place them?
Tests whether values cluster across a whole map, given a neighborhood you choose. Moran's I and Geary's C ask whether neighbors are alike, Getis–Ord G whether high values cluster among themselves, and join counts do the same for categories. The neighbors define the question, so report which ones you used.
A real result
Example “Moran guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
I = 0.18, z = 1.66, p = .097
- I
- 0.1768
- Expected I
- −0.0286
- z
- 1.658
- p
- .097
- Mean neighbors
- 3.333
Plots
View data
| Site | x (standardized) | Average of neighbors (spatial lag) |
|---|---|---|
| 1 | 0.5454 | −0.8669 |
| 2 | −1.037 | −0.0883 |
| 3 | 0.1682 | −0.3159 |
| 4 | −0.0533 | −0.2996 |
| 5 | −0.6288 | −0.9615 |
| 6 | −2.458 | −0.6603 |
| 7 | −0.6966 | −0.2072 |
| 8 | −0.9784 | −0.4460 |
| 9 | 0.1428 | −0.9342 |
| 10 | −0.4381 | 0.2697 |
| 11 | −0.3732 | −0.2797 |
| 12 | −0.6919 | −0.8618 |
| 13 | −0.1885 | −0.5516 |
| 14 | −0.1928 | −0.7356 |
| 15 | −2.488 | 0.2545 |
| 16 | 1.363 | −0.6047 |
| 17 | 0.6401 | −0.0278 |
| 18 | 0.2457 | 0.4761 |
| 19 | −0.7654 | 0.2008 |
| 20 | 0.7127 | 0.1662 |
| 21 | −0.2946 | −0.0414 |
| 22 | −0.1324 | −0.0475 |
| 23 | −1.346 | 0.6642 |
| 24 | 1.480 | 0.2122 |
| 25 | 0.0782 | 0.2199 |
| 26 | 1.918 | 0.6821 |
| 27 | 1.742 | 0.3724 |
| 28 | 0.0880 | 0.6596 |
| 29 | 0.6687 | 0.1725 |
| 30 | 1.737 | 1.110 |
| 31 | −0.4926 | 0.1366 |
| 32 | 0.1951 | 0.4012 |
| 33 | −0.2214 | 0.7657 |
| 34 | 0.3596 | 0.0258 |
| 35 | 0.2109 | 0.7369 |
| 36 | 1.182 | 0.9740 |
Assumptions
- Neighbors chosen for a reason — Neighbors: Rook contiguity, row-standardized (W). The result answers the question for these neighbors; try a second definition as a sensitivity check.
- Values exchangeable under the null — A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals.
- Regions at a meaningful scale — Changing the size or borders of regions can change the result (the modifiable areal unit problem).
- Neighbors: Rook contiguity, row-standardized (W). normal approximation with the randomization variance.
I = 0.18, z = 1.66, p = .097
- I
- 0.1768
- Expected I
- −0.0286
- z
- 1.658
- p
- .097
- Mean neighbors
- 3.333
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Neighbors chosen for a reason — Neighbors: Rook contiguity, row-standardized (W). The result answers the question for these neighbors; try a second definition as a sensitivity check.
- Values exchangeable under the null — A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals.
- Regions at a meaningful scale — Changing the size or borders of regions can change the result (the modifiable areal unit problem).
- Neighbors: Rook contiguity, row-standardized (W). normal approximation with the randomization variance.
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
- Moran guidesp_grid6 · region: site · y: x
- Moran normalitysp_grid6 · region: site · y: x
- Moran permutationsp_grid6 · region: site · y: x
- Moran columbus queensp_columbus · region: site · y: crime
- Moran lonlat knnsp_nc_sids · lat: lat · lon: lon · y: rate
- Moran missing rowssp_nc_missing · region: fips · y: rate
- Geary guidesp_grid6 · region: site · y: x
- Geary permutationsp_columbus · region: site · y: crime
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association
What you need
- Variablenumeric / categorical / boolean · 1 column
- What you measured at each site: a rate or amount, or a category for join counts.
- 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
hypothesis
- Testdefault moran
Which pattern to test for. Choose it before you look at the map.
- Moran's I(default) — Are neighbors alike? The usual first test; sensitive to clustering across the map.
- Geary's C — Are neighbors alike, from squared differences? More sensitive to local differences; below 1 means alike.
- Getis–Ord G — Do high values sit next to high values? For non-negative values; binary weights are the convention.
- Join counts — For categories: are there more same-category neighbor pairs than chance? Uses binary weights.
- Reference distributiondefault permutation
How the p-value is calibrated. Permutation is safest for skewed values and small maps.
- Permutation(default) — Shuffle the values across sites; assumes nothing about their distribution.
- Normal approximation (randomization) — Normal reference with the variance from all rearrangements of the observed values.
- Normal approximation (normality) — Normal reference assuming the values themselves are normal.
- Alternativedefault two_sided
The pattern you expect, stated before testing.
- Either direction(default) — Clustering of like values, or like values kept apart.
- Like values cluster — Positive spatial autocorrelation; for join counts, more same-category neighbors.
- Like values are kept apart — Negative spatial autocorrelation, as on a checkerboard.
- Permutationsdefault 999
Shuffles of the values; the smallest possible p is 1/(B + 1).
- Significance leveldefault 0.05
Level used in the narrative.
options
- 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.
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 defines the question; choose it from how the process could spread, before seeing the result.
Values exchangeable under the null
The test shuffles values across sites; a trend across the map also produces clustering, so remove it first.
Regions at a meaningful scale
Changing region sizes can change the result (the modifiable areal unit problem).
What it reports
- Tests: Values are placed at random across sites
- statistic
- One test of "every component null holds" from several independent tests' p-values.
- expected
- What the statistic would look like with values placed at random across sites, by shuffling them or from a normal approximation.
- variance
- The average squared distance from the mean; the SD squared.
- z
- An estimate in standard-error units, compared with the standard normal distribution.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_analytic
- What the statistic would look like with values placed at random across sites, by shuffling them or from a normal approximation.
- p_perm
- What the statistic would look like with values placed at random across sites, by shuffling them or from a normal approximation.
- n
- How many independent units the analysis used; it sets precision and power.
- links
- Who counts as whose neighbor, and how much. They define the spatial question a test answers.
- mean_neighbours
- Who counts as whose neighbor, and how much. They define the spatial question a test answers.
- islands
- Sites with no neighbors under the chosen rule, such as Hawaii with contiguity.
- n_perm
- How many independent units the analysis used; it sets precision and power.
- kurtosis
- How heavy a distribution's tails are compared with a normal; positive excess means more extreme values.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
- neighbours_label
- How neighbors were defined and weighted, e.g. rook contiguity, row-standardized.
- pattern
- One sentence describing the spatial pattern the test found: clustered, dispersed or random.
- test_label
- Name of the spatial statistic used, e.g. Moran's I, Geary's C or the Clark–Evans test.
- test_symbol
- Symbol of the spatial statistic shown in the APA line, e.g. I, C or R.
Per group, level or term: bb[<level>], bb_expected[<level>], bb_z[<level>], bb_p[<level>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, jsonlite, codesplashr.
Default traps between the two languages
- Both engines read the host's weights and draw permutations from the shared Wichmann–Hill stream, so statistics and permutation p-values match exactly. spdep's moran.mc and joincount.mc use R's generator, so their permutation p differs by Monte Carlo error; the statistics and analytic moments match spdep to 1e-9.
- Two-sided permutation p is twice the smaller tail, capped at 1. spdep's analytic tests use the same normal two-sided p; its permutation functions report one tail.
The exact script CodeSplash ran for example “Moran guide” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.autocorrelation 1.1.1 · spec 24261f9512965509
# Dataset: sp_grid6 (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
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import spatial as sp
from codesplash.stats import spatial_weights as sw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_grid6.parquet", columns=["x", "site"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=sorted(df["site"].dropna().unique()))
df = df.dropna(subset=["x", "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, ["x", "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.autocorrelation/moran-guide/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()
# %% Test
# Global spatial autocorrelation over the neighbors above (Moran 1950; Geary 1954; Getis & Ord 1992;
# Cliff & Ord 1981). Permutation p-values shuffle the values across sites on the shared random stream.
Y = "x"
test = "moran" # moran | geary | getis_ord | join_count
calibration = "randomization" # permutation | randomization | normality
alternative = "two_sided" # two_sided | greater | less
n_perm = int(999)
alpha = 0.05
seed = 42
n = len(df)
cs.check_rows(n, 4, "A spatial autocorrelation test") # the moments need four sites (registry/errors.yaml)
LABELS = {"moran": "Moran's I", "geary": "Geary's C", "getis_ord": "Getis–Ord G", "join_count": "Join counts"}
SYMBOLS = {"moran": "I", "geary": "C", "getis_ord": "G", "join_count": "BW"}
rows = []
if test == "join_count":
# Join counts use binary weights: one link is one join.
if wt["style"] != "B":
wt = {**wt, "w": sw.apply_style(wt["i"], wt["j"], wt["g"], wt["n"], "B"), "style": "B"}
warnings.append("Join counts use binary weights, so the weights style was set to binary for this test.")
vals = df[Y]
if isinstance(vals.dtype, pd.CategoricalDtype):
levels = [str(c) for c in vals.cat.categories]
codes = vals.cat.codes.to_numpy()
else:
uniq = np.sort(vals.unique())
levels = [("true" if u else "false") if isinstance(u, (bool, np.bool_)) else f"{float(u):g}" for u in uniq]
codes = np.searchsorted(uniq, vals.to_numpy())
if len(levels) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=Y, min=2, k=len(levels))
res = sp.join_counts(wt, codes, calibration if calibration == "permutation" else "normal", alternative, n_perm, seed)
rows = res["rows"]
else:
if not pd.api.types.is_numeric_dtype(df[Y]) or pd.api.types.is_bool_dtype(df[Y]):
raise ValueError(f"{LABELS[test]} needs a numeric variable; {Y} is not numeric. Use join counts for categories.")
if test == "getis_ord" and wt["style"] != "B":
warnings.append("Getis–Ord G is usually run with binary weights; row-standardized weights change what it measures.")
check_not_constant(df[Y], Y)
res = sp.global_test(wt, df[Y].to_numpy(dtype=float), test, calibration, alternative, n_perm, seed)
statistic, expected, variance, z, p = res["statistic"], res["expected"], res["variance"], res["z"], res["p"]
# %% Assumptions
assumptions = [
{"key": "weights_chosen", "label": "Neighbors chosen for a reason", "status": "info",
"detail": f"Neighbors: {neighbours_label}. The result answers the question for these neighbors; try a second definition as a sensitivity check."},
{"key": "exchangeable", "label": "Values exchangeable under the null", "status": "info",
"detail": "A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals."},
{"key": "scale", "label": "Regions at a meaningful scale", "status": "info",
"detail": "Changing the size or borders of regions can change the result (the modifiable areal unit problem)."},
]
# %% Result
test_label, test_symbol = LABELS[test], SYMBOLS[test]
clustered = (z > 0) if alternative == "two_sided" else (alternative == "greater")
pattern = ("Like values cluster more than chance alone would explain." if clustered
else "Like values are kept apart more than chance alone would explain.")
if p < alpha:
verdict = pattern
else:
verdict = "The map is compatible with values placed at random across sites."
how = "permutations" if calibration == "permutation" else "normal approximation"
summary = f"{test_label} for {Y}: {test_symbol} = {statistic:.3f} (expected {expected:.3f}), z = {z:.2f}, {cs.fmt_p(p)} ({how}). {verdict}"
values = {"statistic": statistic, "expected": expected, "variance": variance, "z": z, "p": p, "p_analytic": res["p_analytic"],
"p_perm": res["p_perm"] if calibration == "permutation" else None, "n": n, "links": res["links"],
"mean_neighbours": res["links"] / n, "islands": n_islands, "n_perm": n_perm if calibration == "permutation" else 0,
"kurtosis": res.get("kurtosis"), "missing_share": n_dropped / n_input if n_input else 0.0,
"test_label": test_label, "test_symbol": test_symbol, "pattern": pattern, "neighbours_label": neighbours_label}
tables = []
if rows:
for row in rows:
lv = levels[row["level"]]
values[f"bb[{lv}]"] = row["joins"]
values[f"bb_expected[{lv}]"] = row["expected"]
values[f"bb_z[{lv}]"] = row["z"]
values[f"bb_p[{lv}]"] = row["p"]
columns = [{"key": "join", "label": "Join", "type": "string"}, {"key": "joins", "label": "Joins", "type": "number"},
{"key": "expected", "label": "Expected", "type": "number"}, {"key": "variance", "label": "Variance", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}]
table_rows = [{"join": f"{levels[r['level']]}–{levels[r['level']]}", "joins": r["joins"], "expected": r["expected"],
"variance": r["variance"], "z": r["z"], "p": r["p"]} for r in rows]
table_rows.append({"join": "Different categories", "joins": statistic, "expected": expected, "variance": variance, "z": z, "p": p})
tables.append({"key": "joins", "title": "Joins between neighboring sites", "columns": columns, "rows": table_rows})
charts = []
if test != "join_count":
zv = df[Y].to_numpy(dtype=float)
zv = (zv - zv.mean()) / zv.std(ddof=0)
charts.append(cs.chart("scatter", "moran-scatter", f"Each site against its neighbors: {Y}", {
"x": cs.col(f"{Y} (standardized)", zv),
"y": cs.col("Average of neighbors (spatial lag)", sw.weights_lag(wt, zv)),
"site": cs.col("Site", site)}, controls={"slope": statistic if test == "moran" else None}))
if res["null"] is not None:
grid, density = sp.null_curve(res["null"])
charts.append(cs.chart("null", "null-distribution", f"{test_label} under {n_perm} shuffles of the values", {
"x": cs.col(test_symbol, grid), "density": cs.col("Density", density),
"observed": cs.col("Observed", np.full(grid.size, statistic))}))
for key in ["p_perm", "kurtosis"]: # only some options produce these
values.setdefault(key, None)
cs.publish({
"method": "spatial.autocorrelation",
"methodVersion": "1.1.1",
"title": test_label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{test_symbol} = {statistic:.2f}, z = {z:.2f}, {cs.fmt_p(p)}",
"statistics": [{"key": "statistic", "label": test_symbol, "value": statistic}, {"key": "expected", "label": f"Expected {test_symbol}", "value": expected},
{"key": "z", "label": "z", "value": z}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "mean_neighbours", "label": "Mean neighbors", "value": res["links"] / n}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Neighbors: {neighbours_label}. " + (f"p from {n_perm} permutations of the values (seed {seed}); " if calibration == "permutation" else "")
+ ("normal approximation with the randomization variance." if calibration != "normality" else "normal approximation assuming normal values.")],
"values": values,
"charts": charts,
})
The exact script CodeSplash ran for example “Moran guide” · R version 4.5.1 (2025-06-13)
# Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.autocorrelation 1.1.1 · spec 24261f9512965509
# Dataset: sp_grid6 (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_grid6.parquet", col_select = c("x", "site")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = sort(unique(df[["site"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("x", "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("x", "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.autocorrelation/moran-guide/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"]])
# %% Test
# Global spatial autocorrelation over the neighbors above (Moran 1950; Geary 1954; Getis & Ord 1992;
# Cliff & Ord 1981). Permutation p-values shuffle the values across sites on the shared random stream.
Y <- "x"
test <- "moran" # moran | geary | getis_ord | join_count
calibration <- "randomization" # permutation | randomization | normality
alternative <- "two_sided" # two_sided | greater | less
n_perm <- as.integer(999)
alpha <- 0.05
seed <- 42
n <- nrow(df)
cs_check_rows(n, 4, "A spatial autocorrelation test") # the moments need four sites (registry/errors.yaml)
LABELS <- c(moran = "Moran's I", geary = "Geary's C", getis_ord = "Getis–Ord G", join_count = "Join counts")
SYMBOLS <- c(moran = "I", geary = "C", getis_ord = "G", join_count = "BW")
rows <- list()
if (test == "join_count") {
# Join counts use binary weights: one link is one join.
if (wt$style != "B") {
wt$w <- cs_weights_style(wt$i, wt$j, wt$g, wt$n, "B")
wt$style <- "B"
warnings <- c(warnings, "Join counts use binary weights, so the weights style was set to binary for this test.")
}
vals <- df[[Y]]
if (is.factor(vals)) {
levels <- levels(vals)
codes <- as.integer(vals)
} else {
uniq <- sort(unique(vals))
levels <- if (is.logical(uniq)) ifelse(uniq, "true", "false") else sprintf("%g", as.numeric(uniq))
codes <- match(vals, uniq)
}
if (length(levels) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = Y, min = 2, k = length(levels))
res <- cs_sp_join_counts(wt, codes, if (calibration == "permutation") calibration else "normal", alternative, n_perm, seed)
rows <- res$rows
} else {
if (!is.numeric(df[[Y]])) stop(sprintf("%s needs a numeric variable; %s is not numeric. Use join counts for categories.", LABELS[[test]], Y))
if (test == "getis_ord" && wt$style != "B") {
warnings <- c(warnings, "Getis–Ord G is usually run with binary weights; row-standardized weights change what it measures.")
}
cs_check_not_constant(df[[Y]], Y)
res <- cs_sp_global_test(wt, as.numeric(df[[Y]]), test, calibration, alternative, n_perm, seed)
}
statistic <- res$statistic
expected <- res$expected
variance <- res$variance
z <- res$z
p <- res$p
# %% Assumptions
assumptions <- list(
list(key = "weights_chosen", label = "Neighbors chosen for a reason", status = "info",
detail = sprintf("Neighbors: %s. The result answers the question for these neighbors; try a second definition as a sensitivity check.", neighbours_label)),
list(key = "exchangeable", label = "Values exchangeable under the null", status = "info",
detail = "A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals."),
list(key = "scale", label = "Regions at a meaningful scale", status = "info",
detail = "Changing the size or borders of regions can change the result (the modifiable areal unit problem).")
)
# %% Result
test_label <- LABELS[[test]]
test_symbol <- SYMBOLS[[test]]
clustered <- if (alternative == "two_sided") z > 0 else alternative == "greater"
pattern <- if (clustered) "Like values cluster more than chance alone would explain." else "Like values are kept apart more than chance alone would explain."
verdict <- if (p < alpha) pattern else "The map is compatible with values placed at random across sites."
how <- if (calibration == "permutation") "permutations" else "normal approximation"
summary <- sprintf("%s for %s: %s = %.3f (expected %.3f), z = %.2f, %s (%s). %s", test_label, Y, test_symbol, statistic, expected, z, cs_fmt_p(p), how, verdict)
values <- list(statistic = statistic, expected = expected, variance = variance, z = z, p = p, p_analytic = res$p_analytic,
p_perm = if (calibration == "permutation") res$p_perm else NULL, n = n, links = res$links,
mean_neighbours = res$links / n, islands = n_islands, n_perm = if (calibration == "permutation") n_perm else 0L,
kurtosis = res$kurtosis, missing_share = if (n_input > 0) n_dropped / n_input else 0,
test_label = test_label, test_symbol = test_symbol, pattern = pattern, neighbours_label = neighbours_label)
tables <- list()
if (length(rows)) {
for (row in rows) {
lv <- levels[row$level]
values[[sprintf("bb[%s]", lv)]] <- row$joins
values[[sprintf("bb_expected[%s]", lv)]] <- row$expected
values[[sprintf("bb_z[%s]", lv)]] <- row$z
values[[sprintf("bb_p[%s]", lv)]] <- row$p
}
columns <- list(list(key = "join", label = "Join", type = "string"), list(key = "joins", label = "Joins", type = "number"),
list(key = "expected", label = "Expected", type = "number"), list(key = "variance", label = "Variance", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"))
table_rows <- lapply(rows, function(r) list(join = sprintf("%s–%s", levels[r$level], levels[r$level]), joins = r$joins, expected = r$expected,
variance = r$variance, z = r$z, p = r$p))
table_rows[[length(table_rows) + 1L]] <- list(join = "Different categories", joins = statistic, expected = expected, variance = variance, z = z, p = p)
tables[[1]] <- list(key = "joins", title = "Joins between neighboring sites", columns = columns, rows = table_rows)
}
charts <- list()
if (test != "join_count") {
zv <- as.numeric(df[[Y]])
zv <- (zv - mean(zv)) / sqrt(mean((zv - mean(zv))^2))
charts[[length(charts) + 1L]] <- cs_chart("scatter", "moran-scatter", sprintf("Each site against its neighbors: %s", Y), list(
x = cs_col(sprintf("%s (standardized)", Y), zv),
y = cs_col("Average of neighbors (spatial lag)", cs_weights_lag(wt, zv)),
site = cs_col("Site", site)), controls = list(slope = if (test == "moran") statistic else NULL))
}
if (!is.null(res$null)) {
nc <- cs_sp_null_curve(res$null)
charts[[length(charts) + 1L]] <- cs_chart("null", "null-distribution", sprintf("%s under %d shuffles of the values", test_label, n_perm), list(
x = cs_col(test_symbol, nc$x), density = cs_col("Density", nc$density),
observed = cs_col("Observed", rep(statistic, length(nc$x)))))
}
for (key in c("p_perm", "kurtosis")) if (is.null(values[[key]])) values[[key]] <- NA_real_ # only some options produce these
cs_publish(list(
method = "spatial.autocorrelation",
methodVersion = "1.1.1",
title = test_label,
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("%s = %.2f, z = %.2f, %s", test_symbol, statistic, z, cs_fmt_p(p)),
statistics = list(list(key = "statistic", label = test_symbol, value = statistic), list(key = "expected", label = sprintf("Expected %s", test_symbol), value = expected),
list(key = "z", label = "z", value = z), list(key = "p", label = "p", value = p, format = "p"),
list(key = "mean_neighbours", label = "Mean neighbors", value = res$links / n)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Neighbors: %s. ", neighbours_label),
if (calibration == "permutation") sprintf("p from %d permutations of the values (seed %d); ", n_perm, seed) else "",
if (calibration != "normality") "normal approximation with the randomization variance." else "normal approximation assuming normal values.")),
values = values,
charts = charts
))
Sources
- Moran, P. A. P. (1950). Notes on continuous stochastic phenomena. Biometrika, 37, 17–23.
- Geary, R. C. (1954). The contiguity ratio and statistical mapping. The Incorporated Statistician, 5, 115–145.
- Cliff, A. D., & Ord, J. K. (1981). Spatial Processes: Models and Applications. Pion.
- Getis, A., & Ord, J. K. (1992). The analysis of spatial association by use of distance statistics. Geographical Analysis, 24, 189–206.
From the CodeSplash method registry · spatial.autocorrelation v1.1.1.