# Clark-Evans index and nearest-neighbour analysis in R
# https://tidyecology.com/posts/nearest-neighbour-clark-evans/
#
# 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-07

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

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; A <- 1; lambda <- n / A; P <- 4   # unit square: area 1, perimeter 4

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

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)

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)

patterns <- list(CSR = csr, Clustered = clustered, Regular = regular)

## ---- nn-dist ----
nn_dist <- function(p) {
  D <- as.matrix(dist(p)); diag(D) <- Inf
  apply(D, 1, min)
}

## ---- clark-evans ----
clark_evans <- function(p) {
  nn   <- nn_dist(p)
  rbar <- mean(nn)
  e_naive <- 1 / (2 * sqrt(lambda))
  e_don   <- 0.5 * sqrt(A / n) + (0.0514 + 0.041 / sqrt(n)) * P / n
  se <- 0.26136 / sqrt(n * lambda)
  z  <- (rbar - e_naive) / se
  data.frame(
    mean_nn   = rbar,
    R_naive   = rbar / e_naive,
    R_donnelly = rbar / e_don,
    z = z,
    p = 2 * pnorm(-abs(z))
  )
}

ce <- bind_rows(lapply(patterns, clark_evans), .id = "pattern")
ce

## ---- gfun ----
b_dist <- function(p) pmin(p$x, 1 - p$x, p$y, 1 - p$y)   # distance to boundary

G_hat <- function(p, r) {
  nn <- nn_dist(p); bd <- b_dist(p)
  sapply(r, function(rr) {
    keep <- bd >= rr
    if (!any(keep)) NA else mean(nn[keep] <= rr)
  })
}

## ---- ffun ----
set.seed(441)
m_grid <- 40
gx <- rep(seq(0.5 / m_grid, 1 - 0.5 / m_grid, length.out = m_grid), times = m_grid)
gy <- rep(seq(0.5 / m_grid, 1 - 0.5 / m_grid, length.out = m_grid), each  = m_grid)

F_hat <- function(p, r) {
  E <- as.matrix(p[, c("x", "y")])
  d_test <- sapply(seq_along(gx),
                   function(i) sqrt(min((E[, 1] - gx[i])^2 + (E[, 2] - gy[i])^2)))
  bd <- pmin(gx, 1 - gx, gy, 1 - gy)
  sapply(r, function(rr) mean(d_test[bd >= rr] <= rr))
}

## ---- gf-at-r ----
gf_summary <- data.frame(
  pattern    = names(patterns),
  G_at_0.05  = sapply(patterns, function(p) G_hat(p, 0.05)),
  F_at_0.05  = sapply(patterns, function(p) F_hat(p, 0.05)),
  CSR_value  = 1 - exp(-lambda * pi * 0.05^2)
)
gf_summary

## ---- fig-gf ----
r_seq <- seq(0, 0.10, by = 0.004)
theo  <- data.frame(r = r_seq, val = 1 - exp(-lambda * pi * r_seq^2))

curve_df <- function(fun, label) {
  do.call(rbind, lapply(names(patterns), function(nm)
    data.frame(pattern = nm, r = r_seq, val = fun(patterns[[nm]], r_seq), fn = label)))
}
dat <- rbind(curve_df(G_hat, "G(r)"), curve_df(F_hat, "F(r)"))
dat$pattern <- factor(dat$pattern, levels = c("CSR", "Clustered", "Regular"))
dat$fn <- factor(dat$fn, levels = c("G(r)", "F(r)"))
ref <- rbind(cbind(theo, fn = "G(r)"), cbind(theo, fn = "F(r)"))
ref$fn <- factor(ref$fn, levels = c("G(r)", "F(r)"))

ggplot(dat, aes(r, val, colour = pattern)) +
  geom_line(data = ref, aes(r, val), inherit.aes = FALSE,
            colour = te_faint, linetype = "dashed", linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  facet_wrap(~ fn) +
  scale_colour_manual(values = c(CSR = te_faint, Clustered = te_rust, Regular = te_forest)) +
  labs(x = "distance r", y = NULL, colour = NULL) +
  theme_te() + theme(legend.position = "bottom")
