Skip to content

CAssociation · Guide test 253

Join count tests

Test spatial association of categorical labels by counting neighboring label combinations.

Runs in CodeSplashPython (calls R) example not runR example not run

Do it in CodeSplash

In the app, set it up in Analyze with this method:

In Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts), choose Test = Join counts.

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Join count test

7

A side × side grid of areas; neighbors share an edge (rook), weights row-standardized.

0.50

Simultaneous autoregression y = ρWy + ε: positive ρ makes neighbors alike; 0 is no dependence.

0.0

Raises the center block by this much: a local cluster of high values.

1.0

Multiplies the noise in the center block: local heterogeneity in spread.

0.050

Your data

Click an area to test it locally
above the medianat or below

Each area is labeled high or low; the test counts how often neighbors differ.

If H₀ were true

z = 1.71
  1. The reference: how z varies across samples when H₀ is true (normal approximation under random labeling (fewer high–low joins than expected = clustering)).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .043).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

BW=12∑i∑jwij 1[ci≠cj],z=E(BW)−BWVar(BW)BW=\tfrac12\sum_i\sum_jw_{ij}\,\mathbf 1[c_i\ne c_j],\qquad z=\frac{E(BW)-BW}{\sqrt{\mathrm{Var}(BW)}}

With your numbers

BW=10.21,E(BW)=12.50, SD=1.34,z=1.71BW = 10.21,\quad E(BW) = 12.50,\ \mathrm{SD} = 1.34,\quad z = 1.71
cic_i
each area's label: above or at/below the median here
BWBW
joins between differently labeled neighbors; few means clustering

The verdict

z = 1.71, p = .043

p ≤ α = .050: reject H₀

For categorical maps. Dichotomizing a numeric variable discards information, so prefer Moran's I when values are available.

Statistic
1.715
p-value
0.0432
Join count test on a 7 × 7 grid of 49 areas: z = 1.71, p = .043. The p-value is below α = .050, so the data are hard to reconcile with H0.

Join count test on a 7 × 7 grid of 49 areas: z = 1.71, p = .043. The p-value is below α = .050, so the data are hard to reconcile with H₀.

Question and hypotheses

H0: binary/categorical labels are spatially randomly assigned conditional on their totals.

Assumptions

A prespecified spatial weights/neighborhood matrix W, a clearly defined spatial null, and observations whose labels can be permuted under that null. Model residual tests require model-specific adjustments.

Formula

BB=12∑ijwijI(xi=B,xj=B)BW=12∑ijwijI(xi≠xj)\begin{gathered}BB=\tfrac12\sum_{ij}w_{ij}I(x_i=B,x_j=B)\\[5pt] BW=\tfrac12\sum_{ij}w_{ij}I(x_i\ne x_j)\end{gathered}

Parameters and notation

For symmetric binary adjacency the half factor counts each edge once. Other weight conventions require matching normalization.

Structure of the method

Represent categories as labels on a fixed graph, count same- and different-label edges with the correct directed/undirected normalization, and compare counts with conditional random labeling or matching analytic moments. The half factor applies to double-counted symmetric edges, not automatically to every weighted directed graph.

Estimated and nuisance parameters

Estimate category totals and observed join counts. Conditional inference holds the totals fixed; an unconditional random-label model would require category probabilities and a different variance. The test fits no neural weights or spatial regression coefficient and does not estimate the distance scale of an underlying clustering mechanism.

Settings and design choices

Choose category definition, adjacency/weight rule, directed versus undirected treatment, particular joins, and multiplicity strategy. Thresholding a continuous variable to create binary labels loses information and can be data-dependent. The supplied x>0 synthetic rule is fixed, but searching cutoffs for significance is an additional selection step.

Fitting and adaptation

For adaptation, construct scientifically meaningful labels and a stable graph, then retain the chosen fixed-count or other null in permutations. Recalculate adjacency after exclusions only according to a declared rule. Multi-category or multiple-join analyses need explicit joint or adjusted inference rather than many independent-looking unadjusted p values.

Sensitivity and robustness

Inspect rare categories, tiny expected join counts, isolated nodes, graph asymmetry, and dependence created by shared edges. Excess same-label joins can reflect broad composition gradients as well as local interaction. Report raw join counts and label frequencies so a significant standardized result remains interpretable.

How to use and calibrate

Use conditional label permutations or join-count analytic moments; excess same-label joins suggest clustering.

Example application

Test whether presence/absence locations cluster on a neighborhood graph.

Interpretation and pitfalls

Watch out

Directed or asymmetric weights and fixed label totals affect moments. Multiple color/join tests need multiplicity treatment.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.

Python and R

Synthetic 6×6 rook-neighbor lattice; weights and null randomization choices are part of the test. Local tests require multiplicity control before declaring a map of discoveries. localG without self-neighbors is G, not G-star.

Python · invokes R

Not run — Python launcher syntax checked; R backend runtime not verified · needs Python standard library + Rscript; R packages: spdep

# Python launcher for the complete R implementation below.
# Requires Rscript on PATH and the listed R packages.
import shutil
import subprocess
rscript = shutil.which("Rscript")
if rscript is None:
    raise RuntimeError("Install R and make Rscript available on PATH.")
r_code = r"""
set.seed(2026)
nb<-spdep::cell2nb(6,6,type="rook");lw<-spdep::nb2listw(nb,style="W");x<-rnorm(36)
print(spdep::joincount.test(factor(x>0),spdep::nb2listw(nb,style="B")))
"""
# No shell interpolation. A failed R execution raises an error in Python.
result = subprocess.run([rscript, "--vanilla", "-"], input=r_code,
                        text=True, capture_output=True)
print(result.stdout)
if result.stderr:
    print(result.stderr)
result.check_returncode()
R

Not run — Syntax checked; runtime not verified in the final environment · needs spdep

set.seed(2026)
nb<-spdep::cell2nb(6,6,type="rook");lw<-spdep::nb2listw(nb,style="W");x<-rnorm(36)
print(spdep::joincount.test(factor(x>0),spdep::nb2listw(nb,style="B")))

Sources

Statistics guide v4 (historical):
Python: Python launcher syntax checked; R backend runtime not verified · R: Syntax checked; runtime not verified in the final environment
Reference's record:
Edition 2 review: Python: skip · R: not executed (Rscript unavailable); why not run: Python: Python-to-R bridge; Rscript is unavailable. R code was not executed. Python: Not run in the reference's review: Python-to-R bridge; Rscript is unavailable. R code was not executed. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 253, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT253.