# The mean dispersal distance
# https://tidyecology.com/posts/the-mean-dispersal-distance/
#
# 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-14

## ----
knitr::opts_chunk$set(warning = FALSE, message = FALSE)

## ---- kernel-2dt ----
kd_2dt  <- function(r, a, p) (2 * p * r / a^2) * (1 + r^2 / a^2)^(-(p + 1))
m_2dt   <- function(a, p) if (is.na(p)) NA else if (p > 0.5) p * a * (sqrt(pi) / 2) * gamma(p - 0.5) / gamma(p + 1) else Inf
med_2dt <- function(a, p) a * sqrt(2^(1 / p) - 1)
fit_2dt <- function(r) {
  nll <- function(v) { d <- kd_2dt(r, exp(v[1]), exp(v[2])); -sum(log(pmax(d, 1e-300))) }
  o <- tryCatch(optim(c(log(median(r)), 0), nll, method = "BFGS"),
                error = function(e) optim(c(log(median(r)), 0), nll, method = "Nelder-Mead"))
  list(a = exp(o$par[1]), p = exp(o$par[2])) }

set.seed(303)
a_true <- 20; p_true <- 0.85; n <- 500
r <- a_true * sqrt((1 - runif(n))^(-1 / p_true) - 1)   # heavy tail: mean finite, variance infinite
f <- fit_2dt(r)
samp_mean <- mean(r); samp_med <- median(r); samp_max <- max(r)

## ---- mean-vs-p ----
p_grid <- c(0.6, 0.7, 0.85, 1.0, 1.5)
mean_grid <- sapply(p_grid, function(pp) m_2dt(f$a, pp))
med_grid  <- sapply(p_grid, function(pp) med_2dt(f$a, pp))
names(mean_grid) <- names(med_grid) <- p_grid
mean_span <- max(mean_grid) / min(mean_grid)
med_span  <- max(med_grid) / min(med_grid)

## ---- fig-mean-vs-p ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
pg <- seq(0.55, 2, length.out = 400)
dfm <- data.frame(
  p = rep(pg, 2),
  value = c(sapply(pg, function(pp) m_2dt(f$a, pp)), sapply(pg, function(pp) med_2dt(f$a, pp))),
  which = rep(c("mean", "median"), each = length(pg)))
ggplot(dfm, aes(p, value, colour = which)) +
  geom_vline(xintercept = c(0.5, 1), linetype = "dotted", colour = "#9aa69d") +
  geom_vline(xintercept = f$p, linetype = "dashed", colour = "#b5534e") +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c(mean = "#275139", median = "#c9a227")) +
  coord_cartesian(ylim = c(0, 130)) +
  labs(x = "tail exponent p", y = "dispersal distance (m)", colour = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())

## ---- boot ----
set.seed(3033)
B <- 400
bfit <- replicate(B, { rs <- sample(r, n, replace = TRUE)   # refit both parameters on each resample
                       tryCatch(unlist(fit_2dt(rs)), error = function(e) c(a = NA_real_, p = NA_real_)) })
keep <- is.finite(bfit["p", ]) & bfit["p", ] < 50   # is.finite is not enough: drop the rare resample where the optimiser fails to converge and the tail exponent runs off to a huge (but finite) value
bp <- bfit["p", keep]; ba <- bfit["a", keep]
p_ci <- quantile(bp, c(0.025, 0.975))
frac_infvar <- mean(bp <= 1)     # fraction of fits with infinite variance
med_boot <- sapply(bp, function(pp) med_2dt(f$a, pp))
cv_med   <- 100 * sd(med_boot) / mean(med_boot)
mean_boot <- sapply(bp, function(pp) m_2dt(f$a, pp))   # the mean, scale held fixed as in the figure
cv_mean   <- 100 * sd(mean_boot) / mean(mean_boot)
cor_ap    <- cor(ba, bp)                                # refitted scale against refitted exponent
mean_refit <- mapply(m_2dt, ba, bp)                     # both parameters refitted
med_refit  <- mapply(med_2dt, ba, bp)
cv_mean_refit <- 100 * sd(mean_refit) / mean(mean_refit)
cv_med_refit  <- 100 * sd(med_refit) / mean(med_refit)

## ---- infinite-mean ----
set.seed(21)
r_heavy <- 20 * sqrt((1 - runif(2000))^(-1 / 0.45) - 1)   # 2Dt, p = 0.45: population mean does not exist
pop_mean <- m_2dt(20, 0.45)          # analytic population mean
stopifnot(is.infinite(pop_mean))     # it is infinite
emp_mean <- mean(r_heavy)            # sample mean: a finite number
emp_med  <- median(r_heavy)

## ---- fig-running ----
idx <- seq(20, length(r_heavy), by = 5)
run_mean <- cumsum(r_heavy)[idx] / idx
run_med  <- sapply(idx, function(k) median(r_heavy[1:k]))
dfr <- data.frame(n = rep(idx, 2), value = c(run_mean, run_med),
                  which = rep(c("cumulative mean", "cumulative median"), each = length(idx)))
ggplot(dfr, aes(n, value, colour = which)) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c(`cumulative mean` = "#275139", `cumulative median` = "#c9a227")) +
  labs(x = "number of seeds", y = "running estimate (m)", colour = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())
