CSpatial · spatial.points
Point patterns (Clark–Evans, Ripley's K and L envelopes)
Are the points clustered, regularly spaced, or compatible with complete spatial randomness?
For point locations rather than values at sites. The Clark–Evans test compares nearest-neighbor distances with those of random points. Ripley's K and L look at every distance at once, with an envelope from simulated random patterns and a global test that controls error over the whole distance range.
A real result
Example “Clark evans guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
R = 0.987, p = .831, n = 80
- R
- 0.9866
- z
- −0.2129
- p
- .831
- Mean nearest-neighbor distance
- 0.0579
Plots
View data
| x | y |
|---|---|
| 0.6987 | 0.1236 |
| 0.5565 | 0.9515 |
| 0.1401 | 0.7817 |
| 0.2857 | 0.9621 |
| 0.5554 | 0.1143 |
| 0.0251 | 0.9776 |
| 0.4662 | 0.6205 |
| 0.8610 | 0.9274 |
| 0.2525 | 0.2022 |
| 0.5808 | 0.2155 |
| 0.0059 | 0.9219 |
| 0.6919 | 0.7221 |
| 0.2311 | 0.7617 |
| 0.8485 | 0.2853 |
| 0.1538 | 0.3437 |
| 0.3568 | 0.3414 |
| 0.5452 | 0.7880 |
| 0.0012 | 0.3645 |
| 0.3178 | 0.6651 |
| 0.0173 | 0.3728 |
| 0.3416 | 0.1210 |
| 0.3434 | 0.8308 |
| 0.2326 | 0.4183 |
| 0.0614 | 0.0820 |
| 0.4124 | 0.1760 |
| 0.1855 | 0.1810 |
| 0.4107 | 0.6734 |
| 0.1401 | 0.6070 |
| 0.0054 | 0.2595 |
| 0.6017 | 0.5904 |
| 0.9110 | 0.4085 |
| 0.1754 | 0.8664 |
| 0.7312 | 0.1082 |
| 0.0162 | 0.3219 |
| 0.5861 | 0.1683 |
| 0.4258 | 0.0516 |
| 0.2105 | 0.5533 |
| 0.4772 | 0.1419 |
| 0.7548 | 0.1589 |
| 0.4468 | 0.7788 |
| 0.3712 | 0.4437 |
| 0.8748 | 0.1315 |
| 0.4346 | 0.5664 |
| 0.4401 | 0.7739 |
| 0.0820 | 0.4212 |
| 0.0346 | 0.0608 |
| 0.9287 | 0.3854 |
| 0.2946 | 0.4624 |
| 0.5192 | 0.0414 |
| 0.2364 | 0.4107 |
| 0.9718 | 0.3925 |
| 0.6325 | 0.6424 |
| 0.9583 | 0.0359 |
| 0.8864 | 0.0930 |
| 0.5232 | 0.8755 |
| 0.7159 | 0.0042 |
| 0.7406 | 0.1579 |
| 0.0459 | 0.5082 |
| 0.9578 | 0.5589 |
| 0.2011 | 0.3364 |
First 60 of 80 rows.
Assumptions
- Observation window known — The window is the rectangle you stated.
- Constant intensity — Density that varies across the window mimics clustering between points. These tests cannot tell the two apart.
- Distances fixed in advance — Clark–Evans looks only at nearest neighbors, so it can miss a pattern at larger scales.
- Window area 1; Donnelly's edge-corrected mean and standard error; normal approximation.
R = 0.987, p = .831, n = 80
- R
- 0.9866
- z
- −0.2129
- p
- .831
- Mean nearest-neighbor distance
- 0.0579
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Observation window known — The window is the rectangle you stated.
- Constant intensity — Density that varies across the window mimics clustering between points. These tests cannot tell the two apart.
- Distances fixed in advance — Clark–Evans looks only at nearest neighbors, so it can miss a pattern at larger scales.
- Window area 1; Donnelly's edge-corrected mean and standard error; normal approximation.
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
- Clark evans guidesp_guide_points · x_coord: x · y_coord: y
- Clark evans uncorrectedsp_guide_points · x_coord: x · y_coord: y
- Clark evans cellssp_cells · x_coord: x · y_coord: y
- Clark evans redwood simulatedsp_redwood · x_coord: x · y_coord: y
- Ripley guidesp_guide_points · x_coord: x · y_coord: y
- Ripley redwood clusteredsp_redwood · x_coord: x · y_coord: y
- Ripley cells translationsp_cells · x_coord: x · y_coord: y
- Ripley pines bboxsp_japanesepines · x_coord: x · y_coord: y
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
- X or longitudenumeric · 1 column
- Each point's horizontal position, in map units or degrees east.
- Y or latitudenumeric · 1 column
- Each point's vertical position, in map units or degrees north.
Choices you make
hypothesis
- Testdefault ripley
Clark–Evans gives a single number; Ripley's functions show the scale of the pattern.
- Ripley's K and L with an envelope(default) — Looks at every distance up to a maximum: clustering at one scale can sit beside regularity at another.
- Clark–Evans — One number from nearest-neighbor distances: below 1 clustered, above 1 regular.
- Reference distributiondefault normal
How the Clark–Evans p-value is calibrated.
- Normal approximation(default) — Fast and adequate from about 50 points.
- Simulated random patterns — Uniform points with the same count in the same window; better for few points.
- Alternativedefault two_sided
The pattern you expect, stated before testing.
- Either direction(default) — Clustered or regular.
- Clustered — Points closer together than random (R below 1).
- Regular — Points further apart than random (R above 1).
- Global statisticdefault mad
How the deviation from randomness is summed over distance, fixed before looking.
- Maximum absolute deviation(default) — The largest gap between L(r) and r; matches the global envelope.
- Diggle–Cressie–Loosmore–Ford — The squared gap integrated over distance; more power against a pattern spread over many distances.
- Simulated patternsdefault 199
Random patterns for the envelope or simulated p; the smallest possible p is 1/(B + 1).
- Significance leveldefault 0.05
Sets the envelope's width and the narrative's verdict.
options
- Coordinatesdefault planar
What the coordinates are.
- Planar (meters, kilometers, grid units)(default) — Distances are straight lines in the coordinates' own units.
- Longitude and latitude (degrees) — Projected to kilometers at the points' mean latitude; suits a region, not a continent.
- Observation windowdefault bbox
The area in which points could have been found. It sets the intensity and the edge correction.
- Bounding box of the points(default) — Slightly too small, which makes patterns look more regular; state the real window if you know it.
- Stated rectangle — The area actually searched, including where no points were found.
- Window x minimumdefault —
Left edge of the searched rectangle, in the coordinates' units.
- Window x maximumdefault —
Right edge of the searched rectangle, in the coordinates' units.
- Window y minimumdefault —
Bottom edge of the searched rectangle, in the coordinates' units.
- Window y maximumdefault —
Top edge of the searched rectangle, in the coordinates' units.
- Edge correctiondefault isotropic
Points near the edge have neighbors you cannot see; the correction accounts for them.
- Isotropic (Ripley)(default) — Weights each pair by the share of the circle inside the window; the usual choice.
- Translation — Weights each pair by how often its displacement fits inside the window.
- None — No correction: K is biased low at larger distances.
- Edge correctiondefault donnelly
Without a correction, points near the edge look further from their neighbors.
- Donnelly(default) — Corrects the expected distance and its standard error for the window's perimeter.
- None — Original Clark–Evans formula: edges inflate distances, so patterns look more regular.
- Largest distancedefault —
How far to look, fixed before testing. Beyond a quarter of the shorter side, estimates get noisy.
Advanced
- Distances evaluateddefault 129
Grid points from 0 to the largest distance.
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.
Observation window known
A window that is too small makes patterns look regular; too large makes them look clustered.
Constant intensity
Density that varies across the window (more people downtown) mimics clustering between points.
Distances fixed in advance
Choosing the distance after seeing the curve invalidates the p-value; the global test covers the whole range.
What it reports
- Tests: The points follow complete spatial randomness
- statistic
- One test of "every component null holds" from several independent tests' p-values.
- 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.
- n
- How many independent units the analysis used; it sets precision and power.
- area
- The area in which points could have been found. It sets the intensity, and with it what counts as clustered.
- intensity
- The area in which points could have been found. It sets the intensity, and with it what counts as clustered.
- mean_nn
- Mean nearest-neighbor distance over what random points would give; below 1 clustered, above 1 regular.
- expected_nn
- Mean nearest-neighbor distance over what random points would give; below 1 clustered, above 1 regular.
- se_nn
- Mean nearest-neighbor distance over what random points would give; below 1 clustered, above 1 regular.
- T
- How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
- band
- How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
- r_max
- How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
- r_at_max
- How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
- dev_at_max
- How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
- L_at_rmax
- How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
- K_at_rmax
- How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
- n_sim
- How many independent units the analysis used; it sets precision and power.
- level
- How many other points lie within distance r of a typical point, against what random points would give. L(r) = r under randomness.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
- 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.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Simulated patterns come from the shared Wichmann–Hill stream, so envelopes and p-values match across engines. spatstat's own simulations use R's generator; fed the same patterns, its isotropic K, translation K, L and global envelope match the twins to 1e-9.
- Clark–Evans with the Donnelly correction: spatstat pairs the corrected mean with the uncorrected standard error (the guide's p = 0.8103). The twin uses Donnelly's own standard error, which matches the simulated spread of the mean distance under CSR (n = 80: SD 0.00364, Donnelly 0.00368, uncorrected 0.00327), and gives p = 0.8314 on the guide's sample. R itself matches. Calibration: 4.1% rejections at the 5% level over 2,000 patterns of complete spatial randomness (tests/calibration, spatial-clark-evans-donnelly-window); pairing the corrected mean with the uncorrected SE would make z about 1.13 times too large, about 8%.
The exact script CodeSplash ran for example “Clark evans guide” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Point patterns (Clark–Evans, Ripley's K and L envelopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.points 1.0.1 · spec 3ea6162b43a51431
# Dataset: sp_guide_points (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.stats import spatial_points as spp
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_guide_points.parquet", columns=["x", "y"])
n_input = len(df)
df = df.dropna(subset=["x", "y"]) # listwise deletion over the analysis columns
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", "y"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
# Point patterns against complete spatial randomness: Clark & Evans (1954) with Donnelly's (1978) correction, and
# Ripley's K (1977) and Besag's L with an envelope of uniform patterns from the shared random stream.
X = "x"
Y = "y"
test = "clark_evans" # ripley | clark_evans
coordinates = "planar" # planar | lonlat
n_sim = int(199)
alpha = 0.05
seed = 42
px, py = spp.project(df[X].to_numpy(dtype=float), df[Y].to_numpy(dtype=float), coordinates)
n = px.size
wx0, wy0 = spp.project(np.array([0, 1]), np.array([0, 1]), coordinates)
w = spp.window(px, py, "custom", wx0[0], wx0[1], wy0[0], wy0[1], names=(X, Y))
intensity = n / w["area"]
values = {}
tables = []
charts = []
statistics = []
if test == "clark_evans":
correction = "donnelly" # donnelly | none
calibration = "normal" # normal | simulation
alternative = "two_sided" # two_sided | less | greater
res = spp.clark_evans(px, py, w, correction, calibration, alternative, n_sim, seed)
statistic, p = res["R"], res["p"]
test_label, test_symbol = "Clark–Evans test", "R"
if statistic < 1:
pattern = "The points are closer together than random points, a clustered pattern."
else:
pattern = "The points are further apart than random points, a regular pattern."
values.update({"z": res["z"], "p_analytic": res["p_analytic"], "mean_nn": res["mean_nn"], "expected_nn": res["expected_nn"], "se_nn": res["se_nn"],
"n_sim": n_sim if calibration == "simulation" else 0})
detail = f"R = {statistic:.3f} (mean nearest-neighbor distance {res['mean_nn']:.4g}, expected {res['expected_nn']:.4g}), {cs.fmt_p(p)}"
statistics = [{"key": "statistic", "label": "R", "value": statistic}, {"key": "z", "label": "z", "value": res["z"]}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "mean_nn", "label": "Mean nearest-neighbor distance", "value": res["mean_nn"]}]
how = ("Donnelly's edge-corrected mean and standard error" if correction == "donnelly" else "no edge correction") + ("; p from simulated random patterns" if calibration == "simulation" else "; normal approximation")
else:
correction = "isotropic" # isotropic | translation | none
global_stat = "mad" # mad | dclf
rmax = None
r = spp.r_grid(w, n, rmax, int(129))
res = spp.ripley_envelope(px, py, w, r, correction, global_stat, n_sim, alpha, seed)
statistic, p = res["T"], res["p"]
test_label, test_symbol = "Ripley's L envelope test", "T"
if res["dev_at_max"] > 0:
pattern = f"The largest gap is above randomness near distance {res['r_at_max']:.3g}: points cluster at that scale."
else:
pattern = f"The largest gap is below randomness near distance {res['r_at_max']:.3g}: points keep apart at that scale."
values.update({"T": res["T"], "band": res["band"], "r_max": float(r[-1]), "r_at_max": res["r_at_max"], "dev_at_max": res["dev_at_max"],
"L_at_rmax": float(res["L"][-1]), "K_at_rmax": float(res["K"][-1]), "n_sim": n_sim, "level": res["level"]})
detail = f"largest |L(r) − r| = {res['T']:.4g} at distance {res['r_at_max']:.3g}, {cs.fmt_p(p)}" if global_stat == "mad" else f"integrated squared gap {res['T']:.4g}, {cs.fmt_p(p)}"
statistics = [{"key": "statistic", "label": "T", "value": statistic}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "r_at_max", "label": "Distance of largest gap", "value": res["r_at_max"]}]
how = f"{correction} edge correction; global test over distances up to {float(r[-1]):.3g} from {n_sim} uniform patterns"
step = max(1, r.size // 33)
idx = np.arange(0, r.size, step)
tables.append({"key": "curve", "title": "L(r) with its envelopes", "columns": [
{"key": "r", "label": "r", "type": "number"}, {"key": "K", "label": "K(r)", "type": "number"}, {"key": "L", "label": "L(r)", "type": "number"},
{"key": "lo", "label": "Pointwise low", "type": "number"}, {"key": "hi", "label": "Pointwise high", "type": "number"},
{"key": "lo_global", "label": "Global low", "type": "number"}, {"key": "hi_global", "label": "Global high", "type": "number"}],
"rows": [{"r": float(r[k]), "K": float(res["K"][k]), "L": float(res["L"][k]), "lo": float(res["lo"][k]), "hi": float(res["hi"][k]),
"lo_global": float(res["lo_global"][k]), "hi_global": float(res["hi_global"][k])} for k in idx]})
charts.append(cs.chart("envelope", "ripley-envelope", f"L(r) against {n_sim} random patterns", {
"r": cs.col("Distance r", r), "L": cs.col("L(r)", res["L"]), "lo": cs.col("Pointwise low", res["lo"]), "hi": cs.col("Pointwise high", res["hi"]),
"lo_global": cs.col("Global low", res["lo_global"]), "hi_global": cs.col("Global high", res["hi_global"])}, controls={"alpha": alpha}))
charts.insert(0, cs.chart("points", "scatter", f"{n} points", {"x": cs.col(X, df[X].to_numpy(dtype=float)), "y": cs.col(Y, df[Y].to_numpy(dtype=float))}))
# %% Assumptions
assumptions = [
{"key": "window_known", "label": "Observation window known", "status": "pass" if True else "info",
"detail": ("The window is the rectangle you stated." if True
else "The window is the points' bounding box, slightly too small, which makes patterns look more regular. State the searched rectangle if you know it.")},
{"key": "homogeneous", "label": "Constant intensity", "status": "info",
"detail": "Density that varies across the window mimics clustering between points. These tests cannot tell the two apart."},
{"key": "range_fixed", "label": "Distances fixed in advance", "status": "info",
"detail": "Pointwise envelopes do not control error over the whole range; use the global test's p." if test == "ripley" else "Clark–Evans looks only at nearest neighbors, so it can miss a pattern at larger scales."},
]
# %% Result
if p < alpha:
verdict = pattern
else:
verdict = "The points are compatible with complete spatial randomness at this scale."
summary = f"{test_label} for {n} points: {detail}. {verdict}"
values.update({"statistic": statistic, "p": p, "n": n, "area": w["area"], "intensity": intensity, "missing_share": n_dropped / n_input if n_input else 0.0,
"test_label": test_label, "test_symbol": test_symbol, "pattern": pattern})
for key in ["z", "p_analytic", "mean_nn", "expected_nn", "se_nn", "T", "band", "r_max", "r_at_max", "dev_at_max", "L_at_rmax", "K_at_rmax", "level"]: # only some options produce these
values.setdefault(key, None)
cs.publish({
"method": "spatial.points",
"methodVersion": "1.0.1",
"title": test_label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{test_symbol} = {statistic:.3g}, {cs.fmt_p(p)}, n = {n}",
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Window area {w['area']:.4g}; {how}."],
"values": values,
"charts": charts,
})
The exact script CodeSplash ran for example “Clark evans guide” · R version 4.5.1 (2025-06-13)
# Point patterns (Clark–Evans, Ripley's K and L envelopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.points 1.0.1 · spec 3ea6162b43a51431
# Dataset: sp_guide_points (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_guide_points.parquet", col_select = c("x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "y")]), , 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", "y")) # infinite values stop the run (registry/errors.yaml)
# %% Test
# Point patterns against complete spatial randomness: Clark & Evans (1954) with Donnelly's (1978) correction, and
# Ripley's K (1977) and Besag's L with an envelope of uniform patterns from the shared random stream.
X <- "x"
Y <- "y"
test <- "clark_evans" # ripley | clark_evans
coordinates <- "planar" # planar | lonlat
n_sim <- as.integer(199)
alpha <- 0.05
seed <- 42
pr <- cs_spp_project(df[[X]], df[[Y]], coordinates)
px <- pr$x
py <- pr$y
n <- length(px)
wc <- cs_spp_project(c(0, 1), c(0, 1), coordinates)
w <- cs_spp_window(px, py, "custom", wc$x[1], wc$x[2], wc$y[1], wc$y[2], names = c(X, Y))
intensity <- n / w$area
values <- list()
tables <- list()
charts <- list()
if (test == "clark_evans") {
correction <- "donnelly" # donnelly | none
calibration <- "normal" # normal | simulation
alternative <- "two_sided" # two_sided | less | greater
res <- cs_spp_clark_evans(px, py, w, correction, calibration, alternative, n_sim, seed)
statistic <- res$R
p <- res$p
test_label <- "Clark–Evans test"
test_symbol <- "R"
pattern <- if (statistic < 1) "The points are closer together than random points, a clustered pattern." else "The points are further apart than random points, a regular pattern."
values <- c(values, list(z = res$z, p_analytic = res$p_analytic, mean_nn = res$mean_nn, expected_nn = res$expected_nn, se_nn = res$se_nn,
n_sim = if (calibration == "simulation") n_sim else 0L))
detail <- sprintf("R = %.3f (mean nearest-neighbor distance %.4g, expected %.4g), %s", statistic, res$mean_nn, res$expected_nn, cs_fmt_p(p))
statistics <- list(list(key = "statistic", label = "R", value = statistic), list(key = "z", label = "z", value = res$z), list(key = "p", label = "p", value = p, format = "p"),
list(key = "mean_nn", label = "Mean nearest-neighbor distance", value = res$mean_nn))
how <- paste0(if (correction == "donnelly") "Donnelly's edge-corrected mean and standard error" else "no edge correction",
if (calibration == "simulation") "; p from simulated random patterns" else "; normal approximation")
} else {
correction <- "isotropic" # isotropic | translation | none
global_stat <- "mad" # mad | dclf
rmax <- NULL
r <- cs_spp_r_grid(w, n, rmax, as.integer(129))
res <- cs_spp_ripley_envelope(px, py, w, r, correction, global_stat, n_sim, alpha, seed)
statistic <- res$T
p <- res$p
test_label <- "Ripley's L envelope test"
test_symbol <- "T"
pattern <- if (res$dev_at_max > 0) {
sprintf("The largest gap is above randomness near distance %.3g: points cluster at that scale.", res$r_at_max)
} else {
sprintf("The largest gap is below randomness near distance %.3g: points keep apart at that scale.", res$r_at_max)
}
values <- c(values, list(T = res$T, band = res$band, r_max = r[length(r)], r_at_max = res$r_at_max, dev_at_max = res$dev_at_max,
L_at_rmax = res$L[length(r)], K_at_rmax = res$K[length(r)], n_sim = n_sim, level = res$level))
detail <- if (global_stat == "mad") sprintf("largest |L(r) − r| = %.4g at distance %.3g, %s", res$T, res$r_at_max, cs_fmt_p(p)) else sprintf("integrated squared gap %.4g, %s", res$T, cs_fmt_p(p))
statistics <- list(list(key = "statistic", label = "T", value = statistic), list(key = "p", label = "p", value = p, format = "p"),
list(key = "r_at_max", label = "Distance of largest gap", value = res$r_at_max))
how <- sprintf("%s edge correction; global test over distances up to %.3g from %d uniform patterns", correction, r[length(r)], n_sim)
step <- max(1L, length(r) %/% 33L)
idx <- seq(1L, length(r), by = step)
tables[[1]] <- list(key = "curve", title = "L(r) with its envelopes", columns = list(
list(key = "r", label = "r", type = "number"), list(key = "K", label = "K(r)", type = "number"), list(key = "L", label = "L(r)", type = "number"),
list(key = "lo", label = "Pointwise low", type = "number"), list(key = "hi", label = "Pointwise high", type = "number"),
list(key = "lo_global", label = "Global low", type = "number"), list(key = "hi_global", label = "Global high", type = "number")),
rows = lapply(idx, function(k) list(r = r[k], K = res$K[k], L = res$L[k], lo = res$lo[k], hi = res$hi[k], lo_global = res$lo_global[k], hi_global = res$hi_global[k])))
charts[[1]] <- cs_chart("envelope", "ripley-envelope", sprintf("L(r) against %d random patterns", n_sim), list(
r = cs_col("Distance r", r), L = cs_col("L(r)", res$L), lo = cs_col("Pointwise low", res$lo), hi = cs_col("Pointwise high", res$hi),
lo_global = cs_col("Global low", res$lo_global), hi_global = cs_col("Global high", res$hi_global)), controls = list(alpha = alpha))
}
charts <- c(list(cs_chart("points", "scatter", sprintf("%d points", n), list(x = cs_col(X, as.numeric(df[[X]])), y = cs_col(Y, as.numeric(df[[Y]]))))), charts)
# %% Assumptions
custom_window <- TRUE
assumptions <- list(
list(key = "window_known", label = "Observation window known", status = if (custom_window) "pass" else "info",
detail = if (custom_window) {
"The window is the rectangle you stated."
} else {
"The window is the points' bounding box, slightly too small, which makes patterns look more regular. State the searched rectangle if you know it."
}),
list(key = "homogeneous", label = "Constant intensity", status = "info",
detail = "Density that varies across the window mimics clustering between points. These tests cannot tell the two apart."),
list(key = "range_fixed", label = "Distances fixed in advance", status = "info",
detail = if (test == "ripley") "Pointwise envelopes do not control error over the whole range; use the global test's p." else "Clark–Evans looks only at nearest neighbors, so it can miss a pattern at larger scales.")
)
# %% Result
verdict <- if (p < alpha) pattern else "The points are compatible with complete spatial randomness at this scale."
summary <- sprintf("%s for %d points: %s. %s", test_label, n, detail, verdict)
values <- c(values, list(statistic = statistic, p = p, n = n, area = w$area, intensity = intensity, missing_share = if (n_input > 0) n_dropped / n_input else 0,
test_label = test_label, test_symbol = test_symbol, pattern = pattern))
for (key in c("z", "p_analytic", "mean_nn", "expected_nn", "se_nn", "T", "band", "r_max", "r_at_max", "dev_at_max", "L_at_rmax", "K_at_rmax", "level")) if (is.null(values[[key]])) values[[key]] <- NA_real_ # only some options produce these
cs_publish(list(
method = "spatial.points",
methodVersion = "1.0.1",
title = test_label,
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("%s = %.3g, %s, n = %d", test_symbol, statistic, cs_fmt_p(p), n),
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Window area %.4g; %s.", w$area, how)),
values = values,
charts = charts
))
Sources
- Clark, P. J., & Evans, F. C. (1954). Distance to nearest neighbor as a measure of spatial relationships in populations. Ecology, 35, 445–453.
- Donnelly, K. P. (1978). Simulations to determine the variance and edge effect of total nearest-neighbour distance. In Simulation Methods in Archaeology, 91–95. Cambridge University Press.
- Ripley, B. D. (1977). Modelling spatial patterns. JRSS B, 39, 172–212.
- Besag, J. (1977). Discussion of Dr Ripley's paper. JRSS B, 39, 193–195.
- Loosmore, N. B., & Ford, E. D. (2006). Statistical inference using the G or K point pattern spatial statistics. Ecology, 87, 1925–1931.
- Baddeley, A., Rubak, E., & Turner, R. (2015). Spatial Point Patterns. CRC Press.
From the CodeSplash method registry · spatial.points v1.0.1.