# Probability distributions in R: d, p, q and r
# https://tidyecology.com/posts/probability-distributions-in-r/
#
# 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-09-27

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

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

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

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- d-pois ----
lambda <- 2.5                       # mean seedlings per quadrat
round(dpois(0:7, lambda), 4)
sum(dpois(0:100, lambda))           # all the probabilities add up to one

## ---- p-pois ----
ppois(2, lambda)                    # P(X <= 2)
sum(dpois(0:2, lambda))             # the same sum, written out
stopifnot(isTRUE(all.equal(ppois(2, lambda), sum(dpois(0:2, lambda)))))

## ---- binom ----
visits <- 5
p_det  <- 0.3
dbinom(0, size = visits, prob = p_det)     # never detected in five visits

set.seed(1014)
sim_det <- rbinom(1e5, size = visits, prob = p_det)
mean(sim_det == 0)                         # share of simulated ponds with no detection

## ---- binom-numbers ----
miss_exact <- dbinom(0, visits, p_det)
miss_sim   <- mean(sim_det == 0)
miss_mcse  <- sqrt(miss_exact * (1 - miss_exact) / length(sim_det))

## ---- norm ----
dnorm(0.10, mean = 0.10, sd = 0.008)                   # length in metres
dnorm(100, mean = 100, sd = 8)                         # the same newts in millimetres
pnorm(0.11, 0.10, 0.008) - pnorm(0.09, 0.10, 0.008)    # P(0.09 m < length < 0.11 m)
pnorm(110, 100, 8) - pnorm(90, 100, 8)                 # the same interval in millimetres

## ---- norm-numbers ----
dens_m  <- dnorm(0.10, 0.10, 0.008)
dens_mm <- dnorm(100, 100, 8)
p_m     <- pnorm(0.11, 0.10, 0.008) - pnorm(0.09, 0.10, 0.008)
p_mm    <- pnorm(110, 100, 8) - pnorm(90, 100, 8)
stopifnot(dens_m > 1, isTRUE(all.equal(p_m, p_mm)), isTRUE(all.equal(dens_m, 1000 * dens_mm)))

## ---- at-least ----
k <- 3
wrong <- 1 - ppois(k, lambda)                          # P(X > 3), i.e. at least 4
right <- ppois(k - 1, lambda, lower.tail = FALSE)      # P(X > 2), i.e. at least 3
c(wrong = wrong, right = right)

## ---- at-least-checks ----
stopifnot(
  isTRUE(all.equal(ppois(k, lambda), sum(dpois(0:k, lambda)))),                    # default: P(X <= k)
  isTRUE(all.equal(ppois(k, lambda, lower.tail = FALSE), 1 - ppois(k, lambda))),   # FALSE: P(X > k)
  isTRUE(all.equal(right, 1 - ppois(k - 1, lambda))),
  isTRUE(all.equal(right - wrong, dpois(k, lambda)))                               # the missing bar
)
# relative error of the one-minus version for "at least 6"
rel6 <- 100 * (1 - (1 - ppois(6, lambda)) / ppois(5, lambda, lower.tail = FALSE))
stopifnot(rel6 > 100 * (1 - wrong / right))

set.seed(3014)
seedlings <- rpois(1e6, lambda)
sim_at_least <- mean(seedlings >= k)
sim_more     <- mean(seedlings > k)
mcse <- sqrt(sim_at_least * (1 - sim_at_least) / length(seedlings))
round(c(simulated_at_least = sim_at_least, simulated_more_than = sim_more, mc_se = mcse), 4)

## ---- fig-at-least ----
bars <- data.frame(x = 0:10, prob = dpois(0:10, lambda))
bars$part <- ifelse(bars$x < k, "below 3: not counted",
                    ifelse(bars$x == k, "exactly 3: missed by 1 - ppois(3, 2.5)",
                           "4 or more: counted by both"))
bars$part <- factor(bars$part, levels = c("below 3: not counted",
                                          "exactly 3: missed by 1 - ppois(3, 2.5)",
                                          "4 or more: counted by both"))
ggplot(bars, aes(x, prob, fill = part)) +
  geom_col(width = 0.72) +
  geom_text(aes(label = sprintf("%.3f", prob)), vjust = -0.4, size = 3.2, colour = te_ink) +
  annotate("text", x = 6.2, y = 0.262, hjust = 0, size = 3.6, colour = te_forest,
           label = sprintf("at least 3 = %.3f", right)) +
  annotate("text", x = 6.2, y = 0.232, hjust = 0, size = 3.6, colour = te_rust,
           label = sprintf("1 - ppois(3, 2.5) = %.3f", wrong)) +
  scale_fill_manual(values = c("below 3: not counted" = te_line,
                               "exactly 3: missed by 1 - ppois(3, 2.5)" = te_rust,
                               "4 or more: counted by both" = te_forest)) +
  scale_x_continuous(breaks = 0:10) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.08))) +
  labs(x = "seedlings in a quadrat", y = "probability", fill = NULL) +
  theme_datasheet() +
  theme(legend.position = "top", legend.direction = "vertical",
        panel.grid.major.x = element_blank())

## ---- workload ----
n_quadrats <- 120
round(c(booked_with_wrong = n_quadrats * wrong, needed = n_quadrats * right), 1)

## ---- binom-at-least ----
occ_wrong <- 1 - pbinom(2, visits, p_det)
occ_right <- pbinom(1, visits, p_det, lower.tail = FALSE)
c(wrong = occ_wrong, right = occ_right)
stopifnot(isTRUE(all.equal(occ_right - occ_wrong, dbinom(2, visits, p_det))),
          # the negative binomial follows the same rule
          isTRUE(all.equal(pnbinom(2, size = 2, mu = 3, lower.tail = FALSE),
                           1 - sum(dnbinom(0:2, size = 2, mu = 3)))))

## ---- far-tail ----
c(one_minus = 1 - ppois(30, lambda), lower_tail = ppois(30, lambda, lower.tail = FALSE))
stopifnot(1 - ppois(30, lambda) == 0, ppois(30, lambda, lower.tail = FALSE) > 0)

## ---- quantile ----
q95 <- qpois(0.95, lambda)
round(c(q95 = q95, P_at_most_q95 = ppois(q95, lambda), P_at_most_one_less = ppois(q95 - 1, lambda)), 4)
stopifnot(ppois(q95, lambda) >= 0.95, ppois(q95 - 1, lambda) < 0.95,
          # a central 90 per cent interval from qpois() covers at least 0.90
          ppois(q95, lambda) - ppois(qpois(0.05, lambda) - 1, lambda) >= 0.90)

## ---- fig-quantile ----
cdf <- data.frame(x = 0:9, cum = ppois(0:9, lambda))
marks <- data.frame(x = c(q95 - 1, q95), cum = ppois(c(q95 - 1, q95), lambda),
                    lab = c(sprintf("P(X <= %d) = %.3f", q95 - 1, ppois(q95 - 1, lambda)),
                            sprintf("qpois(0.95, 2.5) = %d\nP(X <= %d) = %.3f", q95, q95, ppois(q95, lambda))))
ggplot(cdf, aes(x, cum)) +
  geom_segment(aes(xend = x + 1, yend = cum), colour = te_forest, linewidth = 1) +
  geom_point(colour = te_forest, size = 2.4) +
  geom_hline(yintercept = 0.95, linetype = "dashed", colour = te_rust, linewidth = 0.6) +
  annotate("text", x = 0.2, y = 0.925, label = "target 0.95", hjust = 0, colour = te_rust, size = 3.6) +
  geom_point(data = marks, aes(x, cum), colour = c(te_gold, te_rust), size = 4) +
  geom_text(data = marks, aes(x = x + c(-0.2, 0.25), y = cum - c(0, 0.09), label = lab),
            hjust = c(1, 0), vjust = c(0.5, 0.5), size = 3.4, colour = te_ink, lineheight = 0.95) +
  scale_x_continuous(breaks = 0:10, limits = c(0, 10)) +
  scale_y_continuous(breaks = seq(0, 1, 0.2), limits = c(0, 1.02)) +
  labs(x = "seedlings in a quadrat (x)", y = "P(X <= x)") +
  theme_datasheet()

## ---- nbinom ----
nb_size <- 2; nb_mu <- 3
nb_prob <- nb_size / (nb_size + nb_mu)
set.seed(2014)
draws_prob <- rnbinom(1e5, size = nb_size, prob = nb_prob)
draws_mu   <- rnbinom(1e5, size = nb_size, mu = nb_mu)
nb_check <- rbind(
  stated_prob_form = c(mean = nb_size * (1 - nb_prob) / nb_prob, var = nb_size * (1 - nb_prob) / nb_prob^2),
  simulated_prob   = c(mean(draws_prob), var(draws_prob)),
  stated_mu_form   = c(nb_mu, nb_mu + nb_mu^2 / nb_size),
  simulated_mu     = c(mean(draws_mu), var(draws_mu)))
round(nb_check, 3)
stopifnot(isTRUE(all.equal(nb_check["stated_prob_form", ], nb_check["stated_mu_form", ], check.attributes = FALSE)),
          isTRUE(all.equal(dnbinom(0:20, size = nb_size, prob = nb_prob),
                           dnbinom(0:20, size = nb_size, mu = nb_mu))))

## ---- nbinom-guard ----
# exact moments of the mu form from dnbinom(): mean mu, variance mu + mu^2 / size
nb_x <- 0:2000
nb_p <- dnbinom(nb_x, size = nb_size, mu = nb_mu)
stopifnot(isTRUE(all.equal(sum(nb_x * nb_p), nb_mu)),
          isTRUE(all.equal(sum((nb_x - nb_mu)^2 * nb_p), nb_mu + nb_mu^2 / nb_size)))

## ---- gamma ----
stopifnot(identical(names(formals(rgamma))[1:4], c("n", "shape", "rate", "scale")))
set.seed(4014)
g_positional <- rgamma(1e5, 2, 0.5)                   # read by R as shape = 2, rate = 0.5
g_scale      <- rgamma(1e5, shape = 2, scale = 0.5)   # what a shape-scale reader meant
gamma_check <- rbind(
  positional = c(stated_mean = 2 / 0.5, mean = mean(g_positional), stated_var = 2 / 0.5^2, var = var(g_positional)),
  scale_0.5  = c(2 * 0.5, mean(g_scale), 2 * 0.5^2, var(g_scale)))
round(gamma_check, 3)

## ---- lnorm ----
set.seed(5014)
ml <- log(10); sl <- 0.8
lengths_ln <- rlnorm(1e5, meanlog = ml, sdlog = sl)
round(c(exp_meanlog = exp(ml), sim_median = median(lengths_ln),
        stated_mean = exp(ml + sl^2 / 2), sim_mean = mean(lengths_ln)), 3)

## ---- lnorm-numbers ----
ln_mean <- exp(ml + sl^2 / 2)
ln_sim_mean <- mean(lengths_ln)
ln_sim_med  <- median(lengths_ln)
stopifnot(isTRUE(all.equal(qlnorm(0.5, meanlog = ml, sdlog = sl), exp(ml))))   # exp(meanlog) is the median
