# Complete spatial randomness and quadrat tests in R
# https://tidyecology.com/posts/complete-spatial-randomness-quadrat/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-01

## ---- setup ----
library(ggplot2)
library(dplyr)

# Tidy Ecology palette
te_ink    <- "#16241d"; te_body   <- "#2c3a31"; te_forest <- "#275139"
te_label  <- "#46604a"; te_sage   <- "#93a87f"; te_paper  <- "#f5f4ee"
te_line   <- "#dad9ca"; te_faint  <- "#5d6b61"; te_gold   <- "#c9b458"
te_rust   <- "#b5534e"

theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
      plot.background  = element_rect(fill = te_paper, colour = NA),
      panel.background = element_rect(fill = te_paper, colour = NA),
      text        = element_text(colour = te_body),
      plot.title  = element_text(colour = te_ink, face = "bold"),
      axis.title  = element_text(colour = te_label),
      axis.text   = element_text(colour = te_faint),
      strip.text  = element_text(colour = te_ink, face = "bold"),
      legend.text = element_text(colour = te_body)
    )
}

n <- 200

## ---- csr ----
set.seed(41)
csr <- data.frame(x = runif(n), y = runif(n))

## ---- clustered ----
set.seed(42)
n_parent <- 15
sd_off   <- 0.03
par_x <- runif(n_parent); par_y <- runif(n_parent)
cx <- numeric(0); cy <- numeric(0)
while (length(cx) < n) {
  k  <- sample(n_parent, 1)
  px <- rnorm(1, par_x[k], sd_off)
  py <- rnorm(1, par_y[k], sd_off)
  if (px >= 0 && px <= 1 && py >= 0 && py <= 1) {
    cx <- c(cx, px); cy <- c(cy, py)
  }
}
clustered <- data.frame(x = cx, y = cy)

## ---- regular ----
set.seed(43)
d_min <- 0.038
rx <- numeric(0); ry <- numeric(0)
while (length(rx) < n) {
  px <- runif(1); py <- runif(1)
  if (length(rx) == 0 || min((rx - px)^2 + (ry - py)^2) >= d_min^2) {
    rx <- c(rx, px); ry <- c(ry, py)
  }
}
regular <- data.frame(x = rx, y = ry)

## ---- fig-patterns ----
patterns <- bind_rows(CSR = csr, Clustered = clustered, Regular = regular,
                      .id = "pattern")
patterns$pattern <- factor(patterns$pattern,
                           levels = c("CSR", "Clustered", "Regular"))
grid_lines <- seq(0, 1, by = 0.2)
ggplot(patterns, aes(x, y)) +
  geom_vline(xintercept = grid_lines, colour = te_line, linewidth = 0.3) +
  geom_hline(yintercept = grid_lines, colour = te_line, linewidth = 0.3) +
  geom_point(colour = te_forest, size = 1.1, alpha = 0.85) +
  facet_wrap(~ pattern) +
  coord_equal(expand = FALSE) +
  labs(x = NULL, y = NULL) +
  theme_te() +
  theme(axis.text = element_blank(), panel.grid = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_rect(colour = te_line, fill = NA, linewidth = 0.5))

## ---- quadrat-stats ----
quadrat_stats <- function(p, Q = 5) {
  bx <- cut(p$x, breaks = seq(0, 1, length.out = Q + 1), include.lowest = TRUE)
  by <- cut(p$y, breaks = seq(0, 1, length.out = Q + 1), include.lowest = TRUE)
  counts <- as.vector(table(bx, by))     # all Q * Q cells, zeros included
  expected <- nrow(p) / (Q * Q)
  chi <- sum((counts - expected)^2 / expected)
  data.frame(
    n    = nrow(p),
    mean = mean(counts),
    var  = var(counts),
    vmr  = var(counts) / mean(counts),
    chisq = chi,
    df   = Q * Q - 1,
    p    = pchisq(chi, Q * Q - 1, lower.tail = FALSE)
  )
}

results <- bind_rows(
  CSR       = quadrat_stats(csr),
  Clustered = quadrat_stats(clustered),
  Regular   = quadrat_stats(regular),
  .id = "pattern"
)
results

## ---- identity ----
Q <- 5
data.frame(
  pattern = results$pattern,
  chisq        = results$chisq,
  vmr_identity = (Q * Q - 1) * results$vmr
)
