# Forward selection in RDA: ordistep or ordiR2step
# https://tidyecology.com/posts/forward-selection-in-rda/
#
# 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-09

## ---- setup ----
library(vegan)
library(ggplot2)
library(patchwork)

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),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body),
          strip.text       = element_text(colour = te_ink))
}

## ---- defaults ----
fm_step <- formals(ordistep)
fm_r2   <- formals(ordiR2step)
stopifnot(identical(eval(fm_step$direction)[1], "both"),
          fm_step$Pin == 0.05, fm_step$Pout == 0.1,
          getNperm(eval(fm_step$permutations)) == 199,
          fm_r2$Pin == 0.05, isTRUE(fm_r2$R2scope),
          getNperm(eval(fm_r2$permutations)) == 499,
          isTRUE(fm_step$trace), isTRUE(fm_r2$trace),
          is.null(fm_step$test) || identical(eval(fm_step$test)[1], "permutation"),
          is.null(fm_r2$test) || identical(eval(fm_r2$test)[1], "permutation"))
vegan_version <- packageDescription("vegan")$Version

## ---- design ----
cand_names <- c("moisture", "ph", "nitrogen", "phosphorus", "slope",
                "canopy", "litter", "clay", "grazing", "elevation")
n_site  <- 50      # plots
n_sp    <- 30      # species
n_cand  <- 10      # candidate site variables
nb_size <- 1.5     # negative binomial size
n_perm  <- 99      # permutations in every test below
slope_one   <- 0.4 # species slope SD, one driver design
slope_three <- 0.3 # species slope SD, each of three drivers

make_meadows <- function(n_site, n_cand, slope_sd) {
  env <- as.data.frame(matrix(rnorm(n_site * n_cand), n_site, n_cand))
  names(env) <- cand_names[seq_len(n_cand)]
  eta <- matrix(rnorm(n_sp, 0.5, 1), n_site, n_sp, byrow = TRUE)
  for (k in seq_along(slope_sd)) if (slope_sd[k] > 0)
    eta <- eta + outer(env[[k]], rnorm(n_sp, 0, slope_sd[k]))
  counts <- matrix(rnbinom(n_site * n_sp, mu = exp(eta), size = nb_size),
                   n_site, n_sp)
  counts <- counts[, colSums(counts) > 0, drop = FALSE]
  list(hel = decostand(counts, "hellinger"), env = env)
}
labs_of <- function(m) attr(terms(m), "term.labels")

# the empty model and the model with every candidate, for one dataset
fit_pair <- function(d) {
  own_env <- new.env(parent = globalenv())
  own_env$y_hel <- d$hel
  f_null <- y_hel ~ 1
  f_full <- y_hel ~ .
  environment(f_null) <- own_env
  environment(f_full) <- own_env
  list(null = do.call("rda", list(f_null, data = d$env)),
       full = do.call("rda", list(f_full, data = d$env)))
}

set.seed(3107)
demo_sets  <- lapply(1:8, function(i) make_meadows(n_site, n_cand, slope_one))
demo_empty <- vapply(demo_sets, function(d) {
  m <- fit_pair(d)
  length(labs_of(ordiR2step(m$null, scope = formula(m$full),
                            permutations = n_perm, trace = FALSE))) == 0
}, logical(1))
i_demo <- which(demo_empty)[1]
demo_hel <- demo_sets[[i_demo]]$hel
demo_env <- demo_sets[[i_demo]]$env
demo_fit <- fit_pair(demo_sets[[i_demo]])
mod0    <- demo_fit$null
mod_all <- demo_fit$full
mod_moist <- rda(demo_hel ~ moisture, data = demo_env)
r2_all_demo   <- RsquareAdj(mod_all)$adj.r.squared
r2_moist_demo <- RsquareAdj(mod_moist)$adj.r.squared
set.seed(3108)
p_moist_demo <- anova(mod_moist, permutations = n_perm)$`Pr(>F)`[1]
set.seed(3111)
p_glob_demo  <- anova(mod_all, permutations = n_perm)$`Pr(>F)`[1]
r2_single_demo <- vapply(cand_names, function(v)
  RsquareAdj(rda(demo_hel ~ ., data = demo_env[, v, drop = FALSE]))$adj.r.squared, 0)
stopifnot(names(which.max(r2_single_demo)) == "moisture")
p_min <- 1 / (n_perm + 1)

## ---- trace-demo ----
set.seed(3109)
fit_r2 <- ordiR2step(mod0, scope = formula(mod_all), permutations = n_perm)

## ---- quiet-check ----
n_warn <- 0
fit_r2_quiet <- withCallingHandlers(
  ordiR2step(mod0, scope = formula(mod_all), permutations = n_perm, trace = FALSE),
  warning = function(w) { n_warn <<- n_warn + 1; invokeRestart("muffleWarning") })
stopifnot(length(labs_of(fit_r2_quiet)) == 0, is.null(fit_r2_quiet$anova), n_warn == 0,
          r2_moist_demo > r2_all_demo)

set.seed(3110)
fit_step <- ordistep(mod0, scope = formula(mod_all), permutations = n_perm, trace = FALSE)
step_terms <- labs_of(fit_step)
fit_step$anova

## ---- mainsim ----
r2_hand <- function(yc, ss_tot, xmat)
  sum(qr.fitted(qr(scale(as.matrix(xmat), scale = FALSE)), yc)^2) / ss_tot
adj_r2  <- function(r2, n, p) 1 - (1 - r2) * (n - 1) / (n - p - 1)

run_one <- function(seed, slope_sd, n_site = 50, n_cand = 10, with_step = TRUE) {
  set.seed(seed)
  d <- make_meadows(n_site, n_cand, slope_sd)
  truth <- names(d$env)[which(slope_sd > 0)]
  yc <- scale(as.matrix(d$hel), scale = FALSE); ss <- sum(yc^2)
  adj_of <- function(vars) if (length(vars) == 0) 0 else
    adj_r2(r2_hand(yc, ss, d$env[, vars, drop = FALSE]), n_site, length(vars))
  r2_one <- vapply(seq_len(n_cand),
                   function(k) r2_hand(yc, ss, d$env[, k, drop = FALSE]), 0)
  r2_all <- r2_hand(yc, ss, d$env); b <- which.max(r2_one)
  df_res <- n_site - n_cand - 1
  f_rest <- ((r2_all - r2_one[b]) / (n_cand - 1)) / ((1 - r2_all) / df_res)
  f_last <- NA
  if (length(truth) > 1) {
    r2_t <- r2_hand(yc, ss, d$env[, truth, drop = FALSE])
    f_last <- ((r2_all - r2_t) / (n_cand - length(truth))) / ((1 - r2_all) / df_res)
  }
  # each selected model must be this dataset's model: same adjusted R2 by hand
  terms_of <- function(fit) {
    vars <- labs_of(fit)
    if (length(vars)) stopifnot(abs(RsquareAdj(fit)$adj.r.squared - adj_of(vars)) < 1e-8)
    vars
  }
  m <- fit_pair(d)
  r2s <- terms_of(ordiR2step(m$null, scope = formula(m$full),
                             permutations = n_perm, trace = FALSE))
  # why ordiR2step stopped: 1 ceiling, 2 P value, 3 no rise, 0 nothing left
  rest <- setdiff(names(d$env), r2s); stop_why <- 0; next_true <- NA
  if (length(rest)) {
    nxt <- vapply(rest, function(v) adj_of(c(r2s, v)), 0)
    next_true <- names(which.max(nxt)) %in% truth
    stop_why <- if (max(nxt) <= adj_of(r2s)) 3 else
      if (max(nxt) > adj_r2(r2_all, n_site, n_cand)) 1 else 2
  }
  glob <- anova(m$full, permutations = n_perm)$`Pr(>F)`[1] <= 0.05
  nocap <- character(0)
  if (glob) nocap <- terms_of(ordiR2step(m$null, scope = formula(m$full), R2scope = FALSE,
                                         permutations = n_perm, trace = FALSE))
  stp_true <- NA; stp_noise <- NA
  if (with_step) {
    stp <- terms_of(ordistep(m$null, scope = formula(m$full), permutations = n_perm,
                             trace = FALSE))
    stp_true <- sum(stp %in% truth); stp_noise <- sum(!stp %in% truth)
  }
  c(adj_best = adj_r2(r2_one[b], n_site, 1), adj_all = adj_r2(r2_all, n_site, n_cand),
    best_true = names(d$env)[b] %in% truth, f_rest = f_rest, f_last = f_last,
    glob = glob, r2s_true = sum(r2s %in% truth), r2s_noise = sum(!r2s %in% truth),
    stop_why = stop_why, next_true = next_true,
    nocap_true = sum(nocap %in% truth), nocap_noise = sum(!nocap %in% truth),
    step_true = stp_true, step_noise = stp_noise)
}

n_rep  <- 150   # null and one driver designs, all procedures; fixed in advance
n_side <- 100   # three driver and larger designs, without ordistep
# one seed per dataset, drawn in advance: the meadows do not depend on how
# many random numbers the permutation tests of earlier datasets used
set.seed(2601); seeds_null  <- sample.int(1e6, n_rep)
set.seed(2602); seeds_one   <- sample.int(1e6, n_rep)
set.seed(2603); seeds_three <- sample.int(1e6, n_side)
set.seed(2604); seeds_big   <- sample.int(1e6, n_side)
sim_null  <- sapply(seeds_null, run_one, slope_sd = 0)
sim_one   <- sapply(seeds_one, run_one, slope_sd = slope_one)
sim_three <- sapply(seeds_three, run_one, slope_sd = rep(slope_three, 3),
                    with_step = FALSE)
sim_big   <- sapply(seeds_big, run_one, slope_sd = slope_one, n_site = 120,
                    n_cand = 5, with_step = FALSE)

chk_one <- r2_hand(scale(as.matrix(demo_hel), scale = FALSE),
                   sum(scale(as.matrix(demo_hel), scale = FALSE)^2), demo_env)
stopifnot(abs(adj_r2(chk_one, n_site, n_cand) - r2_all_demo) < 1e-10)

mc_se <- function(p, n) sqrt(p * (1 - p) / n)
one_empty  <- sim_one["r2s_true", ] == 0 & sim_one["r2s_noise", ] == 0
one_ceil   <- sim_one["adj_best", ] > sim_one["adj_all", ]
rate_empty <- mean(one_empty); se_empty <- mc_se(rate_empty, n_rep)
rate_ceil  <- mean(one_ceil)
empty_if_ceil   <- mean(one_empty[one_ceil])
empty_if_noceil <- mean(one_empty[!one_ceil])
f_match    <- all((sim_one["f_rest", ] < 1) == one_ceil)
stopifnot(f_match, all(one_empty[one_ceil]))
best_true_one <- mean(sim_one["best_true", ])
step_keep  <- mean(sim_one["step_true", ] == 1)
big_empty  <- mean(sim_big["r2s_true", ] == 0 & sim_big["r2s_noise", ] == 0)
big_ceil   <- mean(sim_big["adj_best", ] > sim_big["adj_all", ])
big_match  <- mean((sim_big["r2s_true", ] == 0 & sim_big["r2s_noise", ] == 0) ==
                   (sim_big["adj_best", ] > sim_big["adj_all", ]))

## ---- fig-ceiling ----
ceil_df <- data.frame(best = sim_one["adj_best", ], all = sim_one["adj_all", ],
                      outcome = ifelse(one_empty, "empty model", "driver kept"))
ggplot(ceil_df, aes(best, all, colour = outcome)) +
  geom_abline(slope = 1, intercept = 0, colour = te_body, linetype = "dashed",
              linewidth = 0.6) +
  geom_point(size = 2, alpha = 0.85) +
  scale_colour_manual(values = c("driver kept" = te_forest, "empty model" = te_rust),
                      name = NULL) +
  coord_equal() +
  labs(x = "adjusted R2, best single candidate",
       y = "adjusted R2, all ten candidates",
       title = "The ceiling decides at step one",
       subtitle = "below the dashed line the best term exceeds the full model") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- closedform ----
p_cf50  <- pf(1, n_cand - 1, n_site - n_cand - 1)
p_cf120 <- pf(1, 5 - 1, 120 - 5 - 1)

n_gauss <- 4000
set.seed(2605)
f_gauss <- replicate(n_gauss, {
  x_mat <- matrix(rnorm(n_site * n_cand), n_site, n_cand)
  y_vec <- 0.8 * x_mat[, 1] + rnorm(n_site)
  yc <- matrix(y_vec - mean(y_vec)); ss <- sum(yc^2)
  r2_b <- r2_hand(yc, ss, x_mat[, 1, drop = FALSE])
  r2_a <- r2_hand(yc, ss, x_mat)
  ((r2_a - r2_b) / (n_cand - 1)) / ((1 - r2_a) / (n_site - n_cand - 1))
})
rate_gauss <- mean(f_gauss < 1); se_gauss <- mc_se(rate_gauss, n_gauss)

ceiling_only <- function(n_site, n_cand, slope_sd) {
  d <- make_meadows(n_site, n_cand, slope_sd)
  yc <- scale(as.matrix(d$hel), scale = FALSE); ss <- sum(yc^2)
  r2_one <- vapply(seq_len(n_cand),
                   function(k) r2_hand(yc, ss, d$env[, k, drop = FALSE]), 0)
  r2_all <- r2_hand(yc, ss, d$env)
  c(ceil = adj_r2(max(r2_one), n_site, 1) > adj_r2(r2_all, n_site, n_cand),
    best_true = which.max(r2_one) == 1,
    f_rest = ((r2_all - max(r2_one)) / (n_cand - 1)) /
             ((1 - r2_all) / (n_site - n_cand - 1)))
}
slope_grid <- c(0.25, 0.5, 1.0)
n_sweep <- 600
set.seed(2606)
sweep_tab <- do.call(rbind, lapply(list(c(50, 10), c(120, 5)), function(dz) {
  do.call(rbind, lapply(slope_grid, function(s) {
    r <- replicate(n_sweep, ceiling_only(dz[1], dz[2], s))
    data.frame(n_site = dz[1], n_cand = dz[2], slope = s,
               rate = mean(r["ceil", ]), best_true = mean(r["best_true", ]),
               sd_f = sd(r["f_rest", ]))
  }))
}))
sweep_tab$se <- mc_se(sweep_tab$rate, n_sweep)
sw50  <- sweep_tab[sweep_tab$n_site == 50, ]
sw120 <- sweep_tab[sweep_tab$n_site == 120, ]
sd_gauss <- sd(f_gauss)
sw_pool <- c(mean(sw50$rate), mean(sw120$rate))
sw_pool_se <- sqrt(c(sum(sw50$se^2), sum(sw120$se^2))) / 3
z_real <- (sw_pool - c(rate_empty, big_empty)) /
  sqrt(sw_pool_se^2 + c(se_empty, mc_se(big_empty, n_side))^2)

## ---- fig-closedform ----
sweep_tab$design <- factor(sprintf("%d plots, %d candidates", sweep_tab$n_site,
                                   sweep_tab$n_cand),
                           levels = c("50 plots, 10 candidates", "120 plots, 5 candidates"))
cf_df <- data.frame(design = levels(sweep_tab$design), cf = c(p_cf50, p_cf120))
cf_df$design <- factor(cf_df$design, levels = levels(sweep_tab$design))
real_df <- data.frame(design = factor(levels(sweep_tab$design),
                                      levels = levels(sweep_tab$design)),
                      slope = slope_one + c(-0.03, 0.03),
                      rate = c(rate_empty, big_empty),
                      se = c(se_empty, mc_se(big_empty, n_side)))
ggplot(sweep_tab, aes(slope, rate, colour = design)) +
  geom_hline(yintercept = 0.5, colour = te_body, linetype = "dotted", linewidth = 0.5) +
  geom_hline(data = cf_df, aes(yintercept = cf, colour = design),
             linetype = "dashed", linewidth = 0.6) +
  geom_errorbar(aes(ymin = rate - 2 * se, ymax = rate + 2 * se), width = 0.03,
                linewidth = 0.4) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.4) +
  geom_errorbar(data = real_df, aes(ymin = rate - 2 * se, ymax = rate + 2 * se),
                width = 0.03, linewidth = 0.4) +
  geom_point(data = real_df, shape = 23, size = 3, fill = te_paper, stroke = 1) +
  scale_colour_manual(values = c(te_forest, te_gold), name = NULL) +
  scale_y_continuous(limits = c(0.25, 0.75)) +
  labs(x = "species slope SD of the driver (log scale units)",
       y = "share of datasets, driver refused",
       title = "About a coin toss, whatever the driver's strength",
       subtitle = "dotted: one half; bars: two Monte Carlo SE") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- nullrates ----
any_noise <- function(sim, key) mean(sim[key, ] > 0)
null_step  <- any_noise(sim_null, "step_noise")
null_r2s   <- any_noise(sim_null, "r2s_noise")
null_gate  <- mean(sim_null["glob", ] == 1)
null_blan  <- mean(sim_null["glob", ] == 1 & sim_null["r2s_noise", ] > 0)
null_nocap <- any_noise(sim_null, "nocap_noise")
null_ceil  <- mean(sim_null["adj_best", ] > sim_null["adj_all", ])
null_empty <- mean(sim_null["r2s_noise", ] == 0)
step_noise_mean <- mean(sim_null["step_noise", ])
one_blan_keep  <- mean(sim_one["glob", ] == 1 & sim_one["r2s_true", ] == 1)
one_nocap_keep <- mean(sim_one["nocap_true", ] == 1)
one_step_noise <- mean(sim_one["step_noise", ] > 0)
one_r2s_noise  <- mean(sim_one["r2s_noise", ] > 0)
one_nocap_noise <- mean(sim_one["nocap_noise", ] > 0)

## ---- three ----
three_kept <- table(factor(sim_three["r2s_true", ], levels = 0:3))
three_all  <- mean(sim_three["r2s_true", ] == 3)
three_flast <- mean(sim_three["f_last", ] < 1)
three_agree <- mean((sim_three["r2s_true", ] < 3) == (sim_three["f_last", ] < 1))
three_mean_r2s   <- mean(sim_three["r2s_true", ])
three_mean_nocap <- mean(sim_three["nocap_true", ])
p_cf_three <- pf(1, n_cand - 3, n_site - n_cand - 1)
three_one  <- sim_three["r2s_true", ] == 1
three_one_ceil <- sum(three_one & sim_three["stop_why", ] == 1 &
                      sim_three["next_true", ] == 1)
three_kept

## ---- trade ----
rate_row <- function(sim, n, scen, has_step) {
  mk <- function(proc, true_key, noise_key, gate) {
    keep_ok <- if (gate) sim["glob", ] == 1 else rep(TRUE, ncol(sim))
    tr <- sim[true_key, ] * keep_ok; nz <- sim[noise_key, ] * keep_ok
    data.frame(scenario = scen, procedure = proc,
               noise = mean(nz), noise_se = sd(nz) / sqrt(n),
               drivers = mean(tr), drivers_se = sd(tr) / sqrt(n))
  }
  out <- rbind(mk("ordiR2step, defaults", "r2s_true", "r2s_noise", FALSE),
               mk("global test, then ordiR2step", "r2s_true", "r2s_noise", TRUE),
               mk("global test, then R2scope = FALSE", "nocap_true", "nocap_noise", FALSE))
  if (has_step) out <- rbind(mk("ordistep, defaults", "step_true", "step_noise", FALSE), out)
  out
}
proc_lev <- c("ordistep, defaults", "ordiR2step, defaults",
              "global test, then ordiR2step", "global test, then R2scope = FALSE")
scen_lev <- c("no driver", "one driver", "three drivers")
trade_tab <- rbind(rate_row(sim_null, n_rep, scen_lev[1], TRUE),
                   rate_row(sim_one, n_rep, scen_lev[2], TRUE),
                   rate_row(sim_three, n_side, scen_lev[3], FALSE))
trade_tab$procedure <- factor(trade_tab$procedure, levels = proc_lev)
trade_tab$scenario  <- factor(trade_tab$scenario, levels = scen_lev)
tt <- function(scen, proc, col) trade_tab[trade_tab$scenario == scen &
                                          trade_tab$procedure == proc, col]

## ---- fig-trade ----
proc_cols   <- c(te_ink, te_rust, te_gold, te_forest)
proc_shapes <- c(16, 17, 15, 18)
names(proc_cols) <- proc_lev; names(proc_shapes) <- proc_lev
trade_tab <- trade_tab[!is.na(trade_tab$noise), ]
trade_tab$xpos <- as.numeric(trade_tab$scenario) +
  (as.numeric(trade_tab$procedure) - 2.5) * 0.17
trade_plot <- function(dat, yvar, yse, ylab, ttl, ymax, xlo) {
  ggplot(dat, aes(xpos, .data[[yvar]], colour = procedure, shape = procedure)) +
    geom_errorbar(aes(ymin = .data[[yvar]] - 2 * .data[[yse]],
                      ymax = .data[[yvar]] + 2 * .data[[yse]]),
                  width = 0.08, linewidth = 0.5) +
    geom_point(size = 2.8) +
    scale_colour_manual(values = proc_cols, name = NULL, drop = FALSE) +
    scale_shape_manual(values = proc_shapes, name = NULL, drop = FALSE) +
    scale_x_continuous(breaks = seq_along(scen_lev), labels = scen_lev,
                       limits = c(xlo, 3.5)) +
    coord_cartesian(ylim = c(0, ymax)) +
    guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
    labs(x = NULL, y = ylab, title = ttl) +
    theme_datasheet() + theme(panel.grid.major.x = element_blank())
}
p_drv   <- trade_plot(trade_tab[trade_tab$scenario != scen_lev[1], ], "drivers",
                      "drivers_se", "real drivers kept, mean", "Real drivers", 3.05, 1.5)
p_noise <- trade_plot(trade_tab, "noise", "noise_se", "noise variables kept, mean",
                      "Noise variables", max(trade_tab$noise + 2 * trade_tab$noise_se), 0.5)
p_drv + p_noise + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet()) & theme(legend.position = "bottom")
