Using a simulated wetland monitoring dataset, this tutorial begins with an oversimplified model and then examines ecological structure, residual dependence, site effects, heteroscedasticity, influential observations, estimands, robust uncertainty and prediction. The examples can be run in sequence, with each model linked to a specific scientific question.
There is no universally best method for dependent data. The appropriate analysis depends first on the scientific question and only then on the available model or software. Two researchers analysing the same monitoring dataset may reasonably choose different approaches because they seek different quantities, predictions or sources of ecological variation.
Before fitting a model, distinguish four related decisions:
What is the goal of the analysis?
An inferential analysis asks what the data suggest about an ecological relationship or model parameter. A predictive analysis asks how accurately outcomes can be predicted for new observations, sites, species or time periods. An exploratory analysis searches for patterns that can motivate more specific questions.
What quantity should the model estimate?
This target quantity is the estimand. It might be an average association across a monitoring network, a change within the same wetland through time, a site-specific or species-specific response, variation among species in their responses, or a prediction for an unsampled location. Different models can answer different questions even when they use the same response and predictors.
Why might the observations be dependent?
Measurements may share information because they come from the same site, population, species, observer or study; were collected close together in time or space; or involve species with shared evolutionary history. The analysis should represent the aspects of this structure that matter for the scientific question.
How confidently can the dependence structure be
specified?
When the mechanism is scientifically meaningful and sufficiently
supported by the data, it may be represented explicitly through random
effects, correlation functions or structured latent processes. When the
precise structure is uncertain, robust standard errors, dependence-aware
resampling and sensitivity analyses can provide complementary
protection. These strategies are not mutually exclusive.
Consider annual measurements of species richness from the same wetlands. The appropriate starting point depends on what the researcher wants to learn.
| Scientific aim | Example question | Target of the analysis | Useful starting point |
|---|---|---|---|
| Estimate an ecological association while representing repeated observations | How is richness associated with temperature after accounting for persistent differences among wetlands? | A regression association conditional on the specified site and temporal structure | LMM or GLMM, potentially combined with a temporal correlation structure; GLS for Gaussian responses with structured residual covariance |
| Estimate an average association across a population | What is the average change in richness across the monitoring network for a one-unit increase in temperature? | A population-averaged association | GEE |
| Estimate change within the same ecological unit | Are years warmer than a wetland’s usual conditions associated with lower richness within that wetland? | A within-wetland association | Fixed-effects model or a within-between model |
| Quantify ecological heterogeneity | How much does the association between temperature and richness vary among wetlands or species? | Variation in slopes among ecological units | Random-slope LMM or GLMM |
| Estimate a dependence parameter | How persistent are unexplained departures from the expected richness trajectory between neighbouring years? | Temporal correlation after accounting for the systematic component | GLS, LMM or GLMM with an autoregressive structure |
| Protect inference when the dependence model is uncertain | Is the estimated temperature association still supported without assuming an exact within-wetland covariance structure? | The coefficient from the fitted model with dependence-robust uncertainty | Cluster-robust variance estimation or dependence-aware resampling |
| Predict new observations | How accurately can richness be forecast for future years or unsampled wetlands? | Out-of-sample predictive performance | A dependence-aware predictive model evaluated using temporally or spatially blocked validation |
These are starting points rather than rigid rules. For example, an LMM can estimate average regression coefficients, variation among wetlands and wetland-specific predictions within the same model. Robust variance estimation changes how uncertainty is calculated but does not by itself change the coefficient being estimated. Biological interpretation depends on the complete model, including its link function, random effects or covariance structure, and the population to which the conclusion applies.
Before selecting a package or copying a model formula, complete five statements:
My scientific question is: …
The quantity I want to estimate or predict is: …
My observations may be dependent because: …
I want my conclusions to apply to: …
I will judge the analysis by: …
The fourth statement defines the intended scope of inference. A conclusion about the wetlands observed is not necessarily a conclusion about all wetlands, and a model that predicts future observations from monitored sites may not predict an unsampled site. The fifth statement distinguishes goals such as calibrated uncertainty, estimation of ecological heterogeneity and out-of-sample prediction.
Each model in the tutorial is therefore introduced by asking:
What scientific question does this model answer, and what assumptions are required for that answer?
The aim is to connect the scientific question, estimand, dependence structure, inferential method and validation design, rather than to identify one universally superior model.
This tutorial is a code-along page. The core examples use a small set of packages. Advanced examples are shown so that readers can copy and run them after installing the relevant packages.
From the directory containing the file, render the page with:
rmarkdown::render("Expanded_tutorial.Rmd")
If a package is missing, the tutorial does one of two things:
Core code uses base R, ggplot2, nlme,
glmmTMB, sandwich, lmtest,
MASS, and sessioninfo where
available.
Advanced chunks are displayed but skipped if their package is unavailable.
Minimal install for the core tutorial:
install.packages(c(
"rmarkdown", "knitr", "ggplot2", "nlme", "glmmTMB",
"sandwich", "lmtest", "MASS", "sessioninfo"
))
Full install for optional sections:
install.packages(c(
"DHARMa", "geepack", "plm", "brms", "ape", "clubSandwich"
))
On an ordinary laptop, the core examples should render in under a minute after packages are installed. The Bayesian section is intentionally not run by default.
How to use this page. If these models are new to you, begin with the question and guidance box, run the code immediately below it, and compare the output with the accompanying explanation. The advanced sections are labelled optional, and the core workflow does not require every package in the matrix.
Accessibility choices. Plots have captions and alt text in the rendered HTML. Tables have captions where they carry an interpretation. Colour is used to help scanning, but important contrasts are also described in text, point shape, line position, or table values.
Small glossary for the code-along:
This table is useful for troubleshooting, but you do not need to study it before starting the tutorial. The core workflow runs when the core packages are installed; optional packages are skipped or shown without running.
packages <- data.frame(
package = c(
"rmarkdown", "knitr", "nlme", "glmmTMB", "sandwich", "lmtest",
"MASS", "ggplot2", "sessioninfo", "DHARMa", "geepack", "plm", "brms",
"ape", "clubSandwich"
),
role = c(
"render page", "tables and knitting", "GLS and variance structures",
"GLMMs and covariance structures", "robust covariance matrices",
"coefficient tests", "robust regression", "figures", "session information",
"simulation residual diagnostics", "GEE marginal models",
"panel fixed-effects models", "Bayesian models",
"phylogenetic covariance matrices for optional brms examples",
"cluster-robust small-sample corrections"
)
)
packages$installed <- vapply(packages$package, has_pkg, logical(1))
knitr::kable(
packages,
caption = "Packages used in the tutorial and whether they are installed on the rendering machine."
)
| package | role | installed |
|---|---|---|
| rmarkdown | render page | TRUE |
| knitr | tables and knitting | TRUE |
| nlme | GLS and variance structures | TRUE |
| glmmTMB | GLMMs and covariance structures | TRUE |
| sandwich | robust covariance matrices | TRUE |
| lmtest | coefficient tests | TRUE |
| MASS | robust regression | TRUE |
| ggplot2 | figures | TRUE |
| sessioninfo | session information | TRUE |
| DHARMa | simulation residual diagnostics | TRUE |
| geepack | GEE marginal models | FALSE |
| plm | panel fixed-effects models | FALSE |
| brms | Bayesian models | TRUE |
| ape | phylogenetic covariance matrices for optional brms examples | TRUE |
| clubSandwich | cluster-robust small-sample corrections | FALSE |
Minimum learning path:
Core examples in this page are meant to run by default. Optional
examples are explicitly labelled and either skipped when packages are
missing or shown with eval = FALSE.
Question: How do I adapt the tutorial to my dataset?
First map your columns to the concepts used here, then check whether the repeated measurements and time steps suit the proposed model. The template below should produce one row per observation, unambiguous site and year identifiers, and no unexpected duplicates.
Keep in mind: a discrete AR(1) structure assumes
ordered observations and is most straightforward with regular time
steps. Check whether missing years represent genuine gaps before fitting
corAR1(form = ~ year | site).
# Replace these names with the names in your dataset.
my_data <- data.frame(
site = your_site_column,
year = your_year_column,
richness = your_response_column,
temp_anomaly = your_temperature_column,
habitat_quality = your_habitat_column
)
# Basic structure checks.
stopifnot(!anyNA(my_data$site))
stopifnot(!anyNA(my_data$year))
stopifnot(!anyNA(my_data$richness))
# One row per site-year combination?
duplicated_rows <- duplicated(my_data[c("site", "year")])
sum(duplicated_rows)
# How many repeated observations per site?
table(my_data$site)
# Are time steps regular within each site?
time_gaps <- by(my_data$year, my_data$site, function(z) sort(unique(diff(sort(z)))))
time_gaps
# If most sites have gaps larger than one time unit, consider continuous-time
# correlation structures, explicit missing years, or a different validation design.
Source checks. Package claims in this tutorial were checked against primary or official documentation where possible: glmmTMB covariance structures, nlme manual, sandwich vcovCL, DHARMa vignette, brms model fitting, brms AR terms, brms Gaussian-process terms, brms grouping terms, brms phylogenetic models, and the package pages linked in the capability matrix below.
Question: What are systematic structure, residuals and residual dependence?
A model targets a quantity such as a mean, median, other location parameter or transformed mean. The four panels below distinguish the observed data, fitted systematic component, residuals and correlation among those residuals. This is a conceptual decomposition rather than a universal equation.
Keep in mind: in a GLM the systematic component usually acts through a link function, whereas robust or quantile models may target a different location parameter. Normality is not required for the Gauss–Markov optimality result, although it underpins exact small-sample inference in the classical linear model.
set.seed(13)
tiny_year <- 1:20
tiny_signal <- 6 + 0.25 * tiny_year - 0.012 * tiny_year^2
tiny_resid <- make_ar1(20, phi = 0.75, sigma = 0.35)
tiny_y <- tiny_signal + tiny_resid
tiny_fit <- lm(tiny_y ~ poly(tiny_year, 2, raw = TRUE))
tiny_fitted <- fitted(tiny_fit)
tiny_model_resid <- residuals(tiny_fit)
old_par <- par(mfrow = c(2, 2), mar = c(4, 4, 2, 1))
plot(tiny_year, tiny_y, type = "b", pch = 19,
xlab = "Year", ylab = "Observed richness", main = "1. Observed data")
plot(tiny_year, tiny_y, pch = 19, xlab = "Year", ylab = "Richness",
main = "2. Systematic component")
lines(tiny_year, tiny_fitted, col = "#287d8e", lwd = 2)
plot(tiny_year, tiny_model_resid, type = "b", pch = 19,
xlab = "Year", ylab = "Residual", main = "3. Residuals")
abline(h = 0, lty = 2)
acf(tiny_model_resid, main = "4. Residual dependence")
A small teaching example showing observed data, the fitted systematic component, residuals, and residual autocorrelation.
par(old_par)
This view is more general than writing the response simply as “mean plus error” and helps separate model specification from the remaining dependence.
Worked example: annual species richness is simulated for 12 wetland sites. Temperature and habitat quality affect richness, sites differ in baseline richness, and unmeasured ecological conditions persist through time.
The code creates wetland_monitoring, displays its first
rows and plots the site trajectories. Because the data-generating
process is known, we can see what is omitted as the analysis develops
from a simple model to richer alternatives.
Keep in mind: simulation provides a controlled teaching example, not evidence that any method performs well under all conditions.
set.seed(2026)
sites <- paste0("W", sprintf("%02d", 1:12))
years <- 2001:2020
wetland_monitoring <- expand.grid(site = sites, year = years)
wetland_monitoring <- wetland_monitoring[
order(wetland_monitoring$site, wetland_monitoring$year),
]
wetland_monitoring$site <- factor(wetland_monitoring$site)
wetland_monitoring$year_c <- wetland_monitoring$year - mean(years)
annual_temp <- as.numeric(scale(
seq(-1, 1, length.out = length(years)) +
make_ar1(length(years), phi = 0.35, sigma = 0.25)
))
site_quality <- rnorm(length(sites), 0, 0.6)
site_effect <- rnorm(length(sites), 0, 2.2)
names(site_quality) <- sites
names(site_effect) <- sites
wetland_monitoring$temp_anomaly <-
annual_temp[match(wetland_monitoring$year, years)] +
rnorm(nrow(wetland_monitoring), 0, 0.25)
wetland_monitoring$habitat_quality <-
site_quality[as.character(wetland_monitoring$site)] -
0.025 * wetland_monitoring$year_c +
rnorm(nrow(wetland_monitoring), 0, 0.25)
wetland_monitoring$site_effect <-
site_effect[as.character(wetland_monitoring$site)]
wetland_monitoring$epsilon_ar1 <- unlist(lapply(
sites,
function(z) make_ar1(length(years), phi = 0.70, sigma = 1.1)
))
wetland_monitoring$richness <-
24 +
1.7 * wetland_monitoring$temp_anomaly +
3.8 * wetland_monitoring$habitat_quality -
0.025 * wetland_monitoring$year_c^2 +
wetland_monitoring$site_effect +
wetland_monitoring$epsilon_ar1 +
rnorm(nrow(wetland_monitoring), 0, 0.35)
wetland_monitoring$richness <- round(pmax(wetland_monitoring$richness, 1), 1)
wetland_monitoring$year_f <- factor(wetland_monitoring$year, levels = years)
knitr::kable(
head(wetland_monitoring, 10),
caption = "First ten rows of the simulated wetland monitoring dataset."
)
| site | year | year_c | temp_anomaly | habitat_quality | site_effect | epsilon_ar1 | richness | year_f | |
|---|---|---|---|---|---|---|---|---|---|
| 1 | W01 | 2001 | -9.5 | -1.1913302 | 0.1684451 | -0.5603919 | -1.2100950 | 18.8 | 2001 |
| 13 | W01 | 2002 | -8.5 | -0.9827227 | -0.0394787 | -0.5603919 | -0.3691655 | 19.6 | 2002 |
| 25 | W01 | 2003 | -7.5 | -0.7647390 | -0.2161879 | -0.5603919 | -0.9905394 | 18.9 | 2003 |
| 37 | W01 | 2004 | -6.5 | -0.8879428 | -0.2880978 | -0.5603919 | -0.1984479 | 19.5 | 2004 |
| 49 | W01 | 2005 | -5.5 | -0.6401824 | 0.2608134 | -0.5603919 | -0.7417580 | 22.0 | 2005 |
| 61 | W01 | 2006 | -4.5 | -1.2993311 | -0.1377393 | -0.5603919 | 1.5234000 | 22.0 | 2006 |
| 73 | W01 | 2007 | -3.5 | -1.1826443 | 0.1865161 | -0.5603919 | 1.5086659 | 23.8 | 2007 |
| 85 | W01 | 2008 | -2.5 | -0.7651188 | -0.2973563 | -0.5603919 | -0.9949974 | 19.4 | 2008 |
| 97 | W01 | 2009 | -1.5 | -0.3954386 | 0.1621386 | -0.5603919 | 0.8159254 | 23.9 | 2009 |
| 109 | W01 | 2010 | -0.5 | 0.0333591 | -0.0499699 | -0.5603919 | 0.4890839 | 24.4 | 2010 |
site_cols <- grDevices::hcl.colors(length(sites), palette = "Dark 3")
names(site_cols) <- sites
ggplot2::ggplot(wetland_monitoring, ggplot2::aes(year, richness, group = site)) +
ggplot2::geom_line(colour = site_grey, linewidth = 0.5) +
ggplot2::geom_line(
data = subset(wetland_monitoring, site == "W01"),
colour = site_highlight,
linewidth = 0.9
) +
ggplot2::geom_point(
data = subset(wetland_monitoring, site == "W01"),
colour = site_highlight,
size = 1.7
) +
ggplot2::annotate(
"text",
x = max(wetland_monitoring$year) + 0.35,
y = subset(wetland_monitoring, site == "W01")$richness[
nrow(subset(wetland_monitoring, site == "W01"))
],
label = "W01",
hjust = 0,
colour = site_highlight
) +
ggplot2::scale_x_continuous(expand = ggplot2::expansion(mult = c(0.02, 0.12))) +
ggplot2::labs(
title = "Wetland richness through time",
x = "Year",
y = "Species richness"
) +
theme_tutorial()
Simulated richness trajectories for 12 wetland sites from 2001 to 2020. The grey lines show all sites, and site W01 is labelled and highlighted only as a reading guide.
one_site <- subset(wetland_monitoring, site == "W01")
ggplot2::ggplot(one_site, ggplot2::aes(year, richness)) +
ggplot2::geom_line(colour = site_highlight, linewidth = 0.9) +
ggplot2::geom_point(colour = site_highlight, size = 2) +
ggplot2::labs(
title = "One wetland site",
x = "Year",
y = "Species richness"
) +
theme_tutorial()
One wetland site shown by itself so the year-to-year pattern is easy to see.
Question: What happens if a simple temperature–richness model treats every row as independent?
The ordinary linear model provides a slope, but it omits habitat, persistent site differences and temporal memory. These omissions can alter the estimated association as well as make its uncertainty too optimistic. Inspect both the coefficient table and the within-site residual autocorrelation.
Next: add plausible ecological structure before deciding that the remaining pattern is a residual-correlation problem. A small p-value is not persuasive when the model or its standard error is poorly specified.
m_naive <- lm(richness ~ temp_anomaly, data = wetland_monitoring)
knitr::kable(
tidy_coef(m_naive),
caption = "Naive linear model that ignores habitat, site differences, and temporal dependence."
)
| term | estimate | se | statistic | p_value |
|---|---|---|---|---|
| (Intercept) | 24.178 | 0.228 | 106.21 | <0.001 |
| temp_anomaly | 1.461 | 0.228 | 6.42 | <0.001 |
wetland_monitoring$resid_naive <- residuals(m_naive)
old_par <- par(mfrow = c(1, 2))
plot(
wetland_monitoring$year,
wetland_monitoring$resid_naive,
col = site_cols[wetland_monitoring$site],
pch = 19,
xlab = "Year",
ylab = "Residual",
main = "Naive residuals through time"
)
abline(h = 0, lty = 2)
acf(
subset(wetland_monitoring, site == "W01")$resid_naive,
main = "ACF for site W01"
)
Residual diagnostics for the naive model.
par(old_par)
naive_lag <- lag_cor_by_group(wetland_monitoring, "resid_naive")
knitr::kable(
round(naive_lag, 3),
caption = "Within-site residual autocorrelation by lag for the naive model."
)
| lag | mean_autocorrelation | min_site | max_site | n_sites |
|---|---|---|---|---|
| 1 | 0.402 | -0.046 | 0.784 | 12 |
| 2 | 0.236 | -0.238 | 0.724 | 12 |
| 3 | 0.040 | -0.500 | 0.755 | 12 |
| 4 | -0.033 | -0.554 | 0.689 | 12 |
| 5 | -0.012 | -0.549 | 0.711 | 12 |
| 6 | -0.097 | -0.416 | 0.544 | 12 |
plot_lag_correlation(naive_lag, "Naive model residual autocorrelation")
Mean within-site residual autocorrelation for the naive model.
Question: Does the apparent dependence reflect residual autocorrelation or omitted ecological structure?
Add habitat quality and a quadratic year trend, then compare the temperature coefficient and residual lag correlations with the naive model. Temporal structure in the raw data may represent ecological signal; accounting for that signal can reduce, alter or reveal the dependence left in the residuals.
Next: model residual autocorrelation directly if a meaningful pattern remains. An AR(1) term should not be used to absorb an omitted predictor or an obvious trend.
m_systematic <- lm(
richness ~ temp_anomaly + habitat_quality + poly(year_c, 2, raw = TRUE),
data = wetland_monitoring
)
knitr::kable(
tidy_coef(m_systematic),
caption = "Linear model after adding habitat quality and a quadratic year trend."
)
| term | estimate | se | statistic | p_value |
|---|---|---|---|---|
| (Intercept) | 23.887 | 0.252 | 94.63 | <0.001 |
| temp_anomaly | 1.913 | 0.422 | 4.54 | <0.001 |
| habitat_quality | 3.822 | 0.241 | 15.87 | <0.001 |
| poly(year_c, 2, raw = TRUE)1 | 0.022 | 0.073 | 0.30 | 0.761 |
| poly(year_c, 2, raw = TRUE)2 | -0.023 | 0.006 | -4.10 | <0.001 |
temp_compare <- rbind(
extract_term(m_naive, "temp_anomaly", "Naive LM"),
extract_term(m_systematic, "temp_anomaly", "Systematic LM")
)
knitr::kable(
temp_compare,
caption = "Temperature-effect estimate before and after adding systematic ecological structure."
)
| model | estimate | se | statistic | p_value |
|---|---|---|---|---|
| Naive LM | 1.461 | 0.228 | 6.42 | <0.001 |
| Systematic LM | 1.913 | 0.422 | 4.54 | <0.001 |
wetland_monitoring$resid_systematic <- residuals(m_systematic)
systematic_lag <- lag_cor_by_group(wetland_monitoring, "resid_systematic")
lag_compare <- rbind(
data.frame(model = "Naive residuals", naive_lag),
data.frame(model = "After systematic structure", systematic_lag)
)
ggplot2::ggplot(
lag_compare,
ggplot2::aes(x = lag, y = mean_autocorrelation, colour = model)
) +
ggplot2::geom_hline(yintercept = 0, linetype = "dashed", colour = "grey45") +
ggplot2::geom_line(linewidth = 0.8) +
ggplot2::geom_point(size = 2.2) +
ggplot2::scale_colour_manual(
values = c("Naive residuals" = warning_colour,
"After systematic structure" = site_highlight)
) +
ggplot2::labs(
title = "Residual autocorrelation remains after adding biology",
x = "Lag in years",
y = "Mean within-site residual correlation",
colour = NULL
) +
theme_tutorial()
Residual autocorrelation before and after adding systematic ecological structure.
knitr::kable(
round(systematic_lag, 3),
caption = "Within-site residual autocorrelation by lag after adding systematic structure."
)
| lag | mean_autocorrelation | min_site | max_site | n_sites |
|---|---|---|---|---|
| 1 | 0.562 | 0.215 | 0.916 | 12 |
| 2 | 0.374 | 0.044 | 0.824 | 12 |
| 3 | 0.137 | -0.309 | 0.690 | 12 |
| 4 | 0.005 | -0.333 | 0.561 | 12 |
| 5 | -0.119 | -0.383 | 0.477 | 12 |
| 6 | -0.153 | -0.559 | 0.460 | 12 |
In this simulated dataset, adding habitat quality and a year trend changes the temperature estimate and clarifies the ecological signal, but it does not remove residual temporal dependence. The lag-1 residual autocorrelation is still about 0.56, so the next step is to model residual temporal dependence directly rather than declare the problem solved.
Question: How can we represent residual similarity between neighbouring years?
Generalized least squares (GLS) retains the same systematic component while specifying AR(1) residual correlation within each wetland. Compare the coefficient standard errors and inspect the estimated correlation parameter.
Keep in mind: the AR(1) structure should be
biologically plausible and supported by the sampling design. Calling
gls() without a correlation = argument does
not model temporal dependence.
gls_formula <- richness ~ temp_anomaly + habitat_quality +
poly(year_c, 2, raw = TRUE)
# Use maximum likelihood when comparing alternative dependence structures.
m_gls_ind_ml <- nlme::gls(
gls_formula,
data = wetland_monitoring,
method = "ML"
)
m_gls_ar1_ml <- nlme::gls(
gls_formula,
correlation = nlme::corAR1(form = ~ year | site),
data = wetland_monitoring,
method = "ML"
)
knitr::kable(
AIC(m_gls_ind_ml, m_gls_ar1_ml),
caption = "Information-criterion comparison of independence and AR(1) residual structures with the same systematic component."
)
| df | AIC | |
|---|---|---|
| m_gls_ind_ml | 6 | 1112.0868 |
| m_gls_ar1_ml | 7 | 769.9196 |
# After selecting the dependence structure, refit with REML for estimation.
m_gls_ar1 <- update(m_gls_ar1_ml, method = "REML")
knitr::kable(
tidy_coef(m_gls_ar1),
caption = "REML-fitted GLS model with the same systematic terms and AR(1) residual correlation within site."
)
| term | estimate | se | statistic | p_value |
|---|---|---|---|---|
| (Intercept) | 23.979 | 0.621 | 38.61 | <0.001 |
| temp_anomaly | 1.869 | 0.152 | 12.30 | <0.001 |
| habitat_quality | 3.627 | 0.204 | 17.79 | <0.001 |
| poly(year_c, 2, raw = TRUE)1 | -0.014 | 0.055 | -0.26 | 0.795 |
| poly(year_c, 2, raw = TRUE)2 | -0.024 | 0.006 | -3.77 | <0.001 |
phi_hat <- coef(m_gls_ar1$modelStruct$corStruct, unconstrained = FALSE)
knitr::kable(
data.frame(parameter = names(phi_hat), estimate = round(as.numeric(phi_hat), 3)),
caption = "Estimated AR(1) residual correlation parameter from the GLS model."
)
| parameter | estimate |
|---|---|
| Phi | 0.888 |
se_compare <- rbind(
extract_term(m_systematic, "temp_anomaly", "Systematic LM"),
extract_term(m_gls_ar1, "temp_anomaly", "GLS with AR(1)")
)
knitr::kable(
se_compare,
caption = "Temperature-effect comparison between the systematic linear model and GLS AR(1) model."
)
| model | estimate | se | statistic | p_value |
|---|---|---|---|---|
| Systematic LM | 1.913 | 0.422 | 4.54 | <0.001 |
| GLS with AR(1) | 1.869 | 0.152 | 12.30 | <0.001 |
Question: How should repeated measurements from the same wetland be represented?
A random intercept allows each wetland to have its own baseline richness. Fit the Gaussian mixed model and inspect both the fixed effects and site-level variance component.
Keep in mind: persistent differences among sites are distinct from AR(1) residual memory within a site. A random intercept does not automatically remove temporal autocorrelation.
m_site <- glmmTMB::glmmTMB(
richness ~ temp_anomaly + habitat_quality + poly(year_c, 2, raw = TRUE) +
(1 | site),
data = wetland_monitoring
)
knitr::kable(
tidy_coef(m_site),
caption = "Mixed model with a site-level random intercept."
)
| term | estimate | se | statistic | p_value |
|---|---|---|---|---|
| (Intercept) | 23.881 | 0.597 | 40.02 | <0.001 |
| temp_anomaly | 1.918 | 0.232 | 8.27 | <0.001 |
| habitat_quality | 3.849 | 0.311 | 12.39 | <0.001 |
| poly(year_c, 2, raw = TRUE)1 | 0.022 | 0.041 | 0.54 | 0.588 |
| poly(year_c, 2, raw = TRUE)2 | -0.023 | 0.003 | -7.50 | <0.001 |
summary(m_site)$varcor
#>
#> Conditional model:
#> Groups Name Std.Dev.
#> site (Intercept) 1.9937
#> Residual 1.3251
This connects directly to the random-effect syntax in Table 1 of the
Review: (1 | site) means “allow wetland sites to differ in
baseline richness.”
Question: Can hierarchical and temporal residual dependence occur together?
Yes. A wetland may have a persistent baseline while also showing
year-to-year residual memory. The advanced glmmTMB model
below combines a site intercept with an AR(1) time structure; its
variance components and correlation parameter describe different sources
of dependence.
Keep in mind: this is a candidate for sensitivity or multiverse analysis, not an automatic final model. Complex covariance structures can overfit small datasets.
Advanced model warning. The GLS model above is the main
residual-correlation teaching example. The glmmTMB model
below is included because many readers will want to know how site
effects and temporal structure can coexist, but it is easier to overfit
and harder to diagnose. If the residual standard deviation is near zero,
or a variance component looks boundary-like, treat that as a warning to
simplify, check sensitivity, and explain the modelling choice.
The current glmmTMB covariance-structure vignette uses
syntax of the form ar1(time + 0 | group). We use a factor
year to represent regularly spaced annual observations within each
site.
m_combined <- glmmTMB::glmmTMB(
richness ~ temp_anomaly + habitat_quality + poly(year_c, 2, raw = TRUE) +
(1 | site) + ar1(0 + year_f | site),
data = wetland_monitoring
)
knitr::kable(
tidy_coef(m_combined),
caption = "Mixed model with site-level baseline differences and within-site AR(1) temporal dependence."
)
| term | estimate | se | statistic | p_value |
|---|---|---|---|---|
| (Intercept) | 23.964 | 0.625 | 38.35 | <0.001 |
| temp_anomaly | 1.903 | 0.158 | 12.05 | <0.001 |
| habitat_quality | 3.628 | 0.215 | 16.84 | <0.001 |
| poly(year_c, 2, raw = TRUE)1 | -0.010 | 0.041 | -0.23 | 0.814 |
| poly(year_c, 2, raw = TRUE)2 | -0.024 | 0.005 | -5.08 | <0.001 |
summary(m_combined)$varcor
#>
#> Conditional model:
#> Groups Name Std.Dev. Corr
#> site (Intercept) 1.77025
#> site.1 year_f2001 1.50783 0.831 (ar1)
#> Residual 0.53241
In glmmTMB output, the AR(1) term may appear as a
variance component with a label such as site.1 year_f2001
and a correlation line marked (ar1). That label means the
model has created a structured time effect within each site; it does not
mean that only the year 2001 was modelled. A very small residual
standard deviation can also appear when much of the remaining
within-site variation has been allocated to the structured AR(1) term.
In practice, that is a reason to simplify the model or examine
alternative specifications in a sensitivity analysis.
If this model fails or is unstable in a reader’s dataset, the safer teaching move is to return to the GLS AR(1) example and then add complexity one piece at a time.
Question: How should residual plots and diagnostic tests inform the analysis?
Examine residuals against fitted values, through time and across lags, asking whether any remaining structure is large enough to affect the scientific conclusion. Diagnostics guide investigation; they are not automatic model-selection rules.
Keep in mind: statistical significance depends on sample size. Interpret diagnostic tests alongside plots, effect magnitude, model purpose and ecological plausibility rather than adding terms until every test is non-significant.
old_par <- par(mfrow = c(2, 2), mar = c(4, 4, 2.5, 1))
plot(fitted(m_systematic), residuals(m_systematic),
xlab = "Fitted value", ylab = "Residual",
main = "Residuals versus fitted")
abline(h = 0, lty = 2)
plot(wetland_monitoring$year, residuals(m_systematic),
col = site_cols[as.character(wetland_monitoring$site)], pch = 19,
xlab = "Year", ylab = "Residual",
main = "Residuals through time")
abline(h = 0, lty = 2)
acf(subset(wetland_monitoring, site == "W01")$resid_systematic,
main = "ACF for site W01")
plot_lag_correlation_base(systematic_lag, "Across-site lag summary")
Four diagnostic views for the systematic linear model.
par(old_par)
sim_res <- DHARMa::simulateResiduals(
fittedModel = m_combined,
n = 500,
plot = FALSE
)
plot(sim_res)
Optional DHARMa simulation residual diagnostics for the combined model.
# testTemporalAutocorrelation() requires unique time values. Because the dataset
# contains 12 observations per year, aggregate the DHARMa residuals by year for
# a diagnostic of temporal structure shared across sites. Within-site temporal
# dependence is examined separately with the lag summaries above.
sim_res_by_year <- DHARMa::recalculateResiduals(
sim_res,
group = wetland_monitoring$year
)
DHARMa::testTemporalAutocorrelation(
sim_res_by_year,
time = sort(unique(wetland_monitoring$year))
)
Optional DHARMa simulation residual diagnostics for the combined model.
#>
#> Durbin-Watson test
#>
#> data: simulationOutput$scaledResiduals ~ 1
#> DW = 2.6822, p-value = 0.1098
#> alternative hypothesis: true autocorrelation is not 0
DHARMa includes tests for temporal, spatial, and phylogenetic autocorrelation in simulation residuals, but the diagnostic scale must match the scientific question. The code above aggregates residuals by calendar year and therefore evaluates remaining temporal structure shared across sites. It is not a substitute for within-site checks. Repeated spatial or temporal coordinates likewise require aggregation or separate diagnostics for the relevant subgroups.
Question: What if residual variance changes with environmental stress?
Changing variance can itself be ecologically informative: stressful conditions may make richness less predictable. The example increases residual spread with temperature anomaly and compares an ordinary model with a GLS variance model.
Keep in mind: the variance structure must match the
predictor scale. varIdent(form = ~ 1 | group) is intended
for categorical groups; continuous variance covariates can be
represented with structures such as varPower() or
varExp().
set.seed(2027)
dat_het <- wetland_monitoring
dat_het$temp_abs <- abs(dat_het$temp_anomaly) + 0.2
mu_het <-
24 +
1.7 * dat_het$temp_anomaly +
3.8 * dat_het$habitat_quality -
0.025 * dat_het$year_c^2 +
dat_het$site_effect
sigma_het <- 0.5 + 1.1 * dat_het$temp_abs
dat_het$richness <- round(pmax(mu_het + rnorm(nrow(dat_het), 0, sigma_het), 1), 1)
het_formula <- richness ~ temp_anomaly + habitat_quality +
poly(year_c, 2, raw = TRUE) + site
m_het_naive <- lm(het_formula, data = dat_het)
m_het_gls <- nlme::gls(
het_formula,
weights = nlme::varPower(form = ~ temp_abs),
data = dat_het,
method = "REML"
)
knitr::kable(
tidy_coef(m_het_naive),
caption = "Mean model that assumes constant residual variance in the heteroscedastic dataset."
)
| term | estimate | se | statistic | p_value |
|---|---|---|---|---|
| (Intercept) | 23.647 | 0.383 | 61.82 | <0.001 |
| temp_anomaly | 1.682 | 0.277 | 6.08 | <0.001 |
| habitat_quality | 3.622 | 0.391 | 9.26 | <0.001 |
| poly(year_c, 2, raw = TRUE)1 | -0.029 | 0.049 | -0.58 | 0.561 |
| poly(year_c, 2, raw = TRUE)2 | -0.029 | 0.004 | -7.77 | <0.001 |
| siteW02 | 1.832 | 0.500 | 3.66 | <0.001 |
| siteW03 | 0.681 | 0.562 | 1.21 | 0.226 |
| siteW04 | 2.887 | 0.633 | 4.56 | <0.001 |
| siteW05 | 1.207 | 0.509 | 2.37 | 0.019 |
| siteW06 | -1.120 | 0.702 | -1.60 | 0.112 |
| siteW07 | 1.826 | 0.702 | 2.60 | 0.010 |
| siteW08 | -1.309 | 0.505 | -2.59 | 0.010 |
| siteW09 | -2.248 | 0.574 | -3.92 | <0.001 |
| siteW10 | 2.111 | 0.678 | 3.11 | 0.002 |
| siteW11 | -2.524 | 0.502 | -5.03 | <0.001 |
| siteW12 | 1.045 | 0.510 | 2.05 | 0.042 |
knitr::kable(
tidy_coef(m_het_gls),
caption = "GLS model with the same systematic component and residual variance changing with temperature anomaly."
)
| term | estimate | se | statistic | p_value |
|---|---|---|---|---|
| (Intercept) | 23.347 | 0.289 | 80.78 | <0.001 |
| temp_anomaly | 1.755 | 0.245 | 7.16 | <0.001 |
| habitat_quality | 3.543 | 0.334 | 10.60 | <0.001 |
| poly(year_c, 2, raw = TRUE)1 | -0.043 | 0.040 | -1.07 | 0.288 |
| poly(year_c, 2, raw = TRUE)2 | -0.029 | 0.003 | -8.42 | <0.001 |
| siteW02 | 2.069 | 0.414 | 5.00 | <0.001 |
| siteW03 | 0.895 | 0.465 | 1.92 | 0.056 |
| siteW04 | 3.365 | 0.518 | 6.49 | <0.001 |
| siteW05 | 1.907 | 0.393 | 4.85 | <0.001 |
| siteW06 | -0.708 | 0.575 | -1.23 | 0.220 |
| siteW07 | 1.999 | 0.587 | 3.41 | <0.001 |
| siteW08 | -0.855 | 0.404 | -2.12 | 0.035 |
| siteW09 | -1.847 | 0.470 | -3.93 | <0.001 |
| siteW10 | 2.498 | 0.523 | 4.78 | <0.001 |
| siteW11 | -2.235 | 0.410 | -5.46 | <0.001 |
| siteW12 | 1.376 | 0.415 | 3.32 | 0.001 |
het_plot_data <- rbind(
data.frame(
temp_anomaly = dat_het$temp_anomaly,
residual = residuals(m_het_naive),
model = "Naive LM residual"
),
data.frame(
temp_anomaly = dat_het$temp_anomaly,
residual = residuals(m_het_gls, type = "normalized"),
model = "Normalized GLS residual"
)
)
ggplot2::ggplot(het_plot_data, ggplot2::aes(temp_anomaly, residual)) +
ggplot2::geom_hline(yintercept = 0, linetype = "dashed", colour = "grey45") +
ggplot2::geom_point(alpha = 0.7, colour = site_highlight, size = 1.7) +
ggplot2::facet_wrap(~ model, nrow = 1, scales = "free_y") +
ggplot2::labs(
x = "Temperature anomaly",
y = "Residual",
title = "Residual spread before and after a variance model"
) +
theme_tutorial()
Residual spread before and after modelling heteroscedasticity.
This example provides the practical counterpart to Box 2 of the Review.
Question: How should extreme years or sites be handled?
Extreme observations may be data errors, rare ecological events or signs of model misspecification. Add several identifiable extremes, compare ordinary and robust fits, and report whether the estimated temperature association changes materially.
Keep in mind: sensitivity analysis is usually preferable to automatic deletion. Biologically real extremes should not be removed solely because they exert strong influence on the fitted model.
set.seed(2026)
dat_outlier <- wetland_monitoring
outlier_rows <- sample(seq_len(nrow(dat_outlier)), 5)
dat_outlier$richness[outlier_rows] <- dat_outlier$richness[outlier_rows] +
sample(c(-9, 10, 12), length(outlier_rows), replace = TRUE)
dat_outlier$outlier_added <- seq_len(nrow(dat_outlier)) %in% outlier_rows
m_out_lm <- lm(richness ~ temp_anomaly + habitat_quality, data = dat_outlier)
m_out_robust <- MASS::rlm(richness ~ temp_anomaly + habitat_quality,
data = dat_outlier)
outlier_compare <- rbind(
extract_term(m_out_lm, "temp_anomaly", "Ordinary LM"),
data.frame(
model = "Robust regression (MASS::rlm)",
estimate = round(coef(m_out_robust)["temp_anomaly"], 3),
se = NA_real_,
statistic = NA_real_,
p_value = NA_character_
)
)
knitr::kable(
outlier_compare,
caption = "Sensitivity of the temperature-effect estimate to ordinary versus robust regression."
)
| model | estimate | se | statistic | p_value | |
|---|---|---|---|---|---|
| 1 | Ordinary LM | 1.903 | 0.196 | 9.73 | <0.001 |
| temp_anomaly | Robust regression (MASS::rlm) | 1.906 | NA | NA | NA |
dat_outlier$resid_lm <- residuals(m_out_lm)
dat_outlier$outlier_label <- ifelse(dat_outlier$outlier_added,
"added extreme row", "ordinary row")
ggplot2::ggplot(dat_outlier, ggplot2::aes(temp_anomaly, resid_lm)) +
ggplot2::geom_hline(yintercept = 0, linetype = "dashed", colour = "grey45") +
ggplot2::geom_point(
ggplot2::aes(shape = outlier_label, colour = outlier_label),
size = 2,
alpha = 0.85
) +
ggplot2::scale_shape_manual(values = c("added extreme row" = 17,
"ordinary row" = 19)) +
ggplot2::scale_colour_manual(values = c("added extreme row" = warning_colour,
"ordinary row" = site_highlight)) +
ggplot2::labs(
title = "Extreme observations are visible",
x = "Temperature anomaly",
y = "LM residual",
shape = NULL,
colour = NULL
) +
theme_tutorial()
Residual plot with added extreme observations marked by triangles.
The robust fit assesses sensitivity to extreme observations. It does not account for temporal or clustered dependence, which would require an additional modelling or inferential strategy.
Question: Do GLMMs, GEEs and fixed-effects models answer the same question?
Not necessarily. Decomposing temperature into within-site and between-site components shows how closely related models can target different estimands. A within-site coefficient describes years when a wetland is warmer than its own average; a between-site coefficient contrasts wetlands with different average temperatures.
Keep in mind: conditional effects account for the specified site structure, whereas marginal effects average across the population. Differences between estimands are not evidence of a robustness failure unless the models were intended to answer the same question.
dat_within <- wetland_monitoring
dat_within$temp_site_mean <- ave(dat_within$temp_anomaly, dat_within$site)
dat_within$temp_within <- dat_within$temp_anomaly - dat_within$temp_site_mean
m_population <- lm(
richness ~ temp_anomaly + habitat_quality + poly(year_c, 2, raw = TRUE),
data = dat_within
)
m_within_between <- lm(
richness ~ temp_within + temp_site_mean + habitat_quality +
poly(year_c, 2, raw = TRUE),
data = dat_within
)
estimand_compare <- rbind(
extract_term(m_population, "temp_anomaly", "Pooled temperature effect"),
extract_term(m_within_between, "temp_within", "Within-site temperature effect"),
extract_term(m_within_between, "temp_site_mean", "Between-site temperature contrast")
)
knitr::kable(
estimand_compare,
caption = "A within-between decomposition separates different temperature estimands."
)
| model | estimate | se | statistic | p_value |
|---|---|---|---|---|
| Pooled temperature effect | 1.913 | 0.422 | 4.54 | <0.001 |
| Within-site temperature effect | 1.918 | 0.423 | 4.53 | <0.001 |
| Between-site temperature contrast | 0.769 | 5.787 | 0.13 | 0.894 |
The pooled temperature coefficient mixes two questions: what happens when a site is warmer than usual, and how warmer sites differ from cooler sites. The within-between decomposition separates these. This is often called a Mundlak-style decomposition in panel-data discussions. Because this teaching dataset uses a Gaussian model with an identity link, conditional and population-average slopes are often closer in interpretation than they would be in logistic or other nonlinear-link models. The main contrast here is therefore pooled versus within- and between-site effects, not a claim that every GLMM and GEE coefficient must differ.
m_conditional_mundlak <- glmmTMB::glmmTMB(
richness ~ temp_within + temp_site_mean + habitat_quality +
poly(year_c, 2, raw = TRUE) + (1 | site),
data = dat_within
)
cond_terms <- tidy_coef(m_conditional_mundlak)
cond_terms <- cond_terms[
cond_terms$term %in% c("temp_within", "temp_site_mean", "habitat_quality"),
]
knitr::kable(
cond_terms,
caption = "Conditional mixed model with within-site and between-site temperature terms."
)
| term | estimate | se | statistic | p_value | |
|---|---|---|---|---|---|
| 2 | temp_within | 1.918 | 0.232 | 8.27 | <0.001 |
| 3 | temp_site_mean | 0.749 | 18.628 | 0.04 | 0.968 |
| 4 | habitat_quality | 3.853 | 0.316 | 12.19 | <0.001 |
The conditional mixed model asks about temperature after allowing wetland sites to differ in baseline richness. The within-site term is usually closest to the question “what happens when this site is warmer than its own average?”
Not run on this machine: the geepack
package is not installed. The code is shown so readers can run it after
installing the package.
dat_within <- dat_within[order(dat_within$site, dat_within$year), , drop = FALSE]
stopifnot(!is.unsorted(as.integer(dat_within$site)))
m_gee <- geepack::geeglm(
richness ~ temp_within + temp_site_mean + habitat_quality +
poly(year_c, 2, raw = TRUE),
id = site,
waves = year,
corstr = "ar1",
data = dat_within
)
summary(m_gee)
This GEE fit has only 12 independent site clusters. It is included to clarify the population-averaged estimand and working-correlation syntax, not to support precise large-sample inference. In an applied analysis, assess whether the number of clusters is adequate and consider an appropriate small-sample correction where available.
Not run on this machine: the plm package
is not installed. The code is shown so readers can run it after
installing the package.
m_plm <- plm::plm(
richness ~ temp_anomaly + habitat_quality + poly(year_c, 2, raw = TRUE),
data = dat_within,
index = c("site", "year"),
model = "within"
)
summary(m_plm)
Question: Can inference be made less sensitive to an uncertain within-site correlation structure?
Cluster-robust standard errors adjust uncertainty without changing the fitted ecological model. Compare ordinary and site-clustered standard errors, making sure that the clustering level reflects the sampling process.
Keep in mind: robust standard errors require enough independent clusters; report the clustering level and use a small-sample correction such as CR2 when available. They do not repair an omitted predictor, an unsuitable response distribution or biased sampling.
m_lm_cluster <- lm(
richness ~ temp_anomaly + habitat_quality,
data = wetland_monitoring
)
ordinary <- tidy_coef(m_lm_cluster)
n_site_clusters <- length(unique(wetland_monitoring$site))
V_cluster <- sandwich::vcovCL(
m_lm_cluster,
cluster = wetland_monitoring$site,
type = "HC1"
)
clustered_test <- lmtest::coeftest(m_lm_cluster, vcov. = V_cluster)
clustered <- data.frame(
term = rownames(clustered_test),
estimate = round(clustered_test[, 1], 3),
se = round(clustered_test[, 2], 3),
row.names = NULL
)
ordinary <- ordinary[, c("term", "estimate", "se")]
ordinary$model <- "ordinary model-based SE"
clustered$model <- "site-clustered HC1 SE"
robust_compare <- rbind(ordinary, clustered)
robust_compare <- robust_compare[
robust_compare$term %in% c("temp_anomaly", "habitat_quality"),
c("model", "term", "estimate", "se")
]
knitr::kable(
robust_compare,
caption = paste(
"Ordinary standard errors versus illustrative site-clustered robust standard errors.",
"There are", n_site_clusters, "site clusters."
)
)
| model | term | estimate | se | |
|---|---|---|---|---|
| 2 | ordinary model-based SE | temp_anomaly | 1.923 | 0.165 |
| 3 | ordinary model-based SE | habitat_quality | 3.762 | 0.246 |
| 5 | site-clustered HC1 SE | temp_anomaly | 1.923 | 0.221 |
| 6 | site-clustered HC1 SE | habitat_quality | 3.762 | 0.892 |
With only 12 site clusters, the HC1 cluster-robust standard errors
above are a teaching comparison rather than a basis for asymptotic
p-values. In an applied analysis, prefer a small-sample correction such
as CR2 with Satterthwaite degrees of freedom when
clubSandwich supports the fitted model.
Not run on this machine: the clubSandwich
package is not installed. The code is shown so readers can run it after
installing the package.
clubSandwich::coef_test(
m_lm_cluster,
vcov = "CR2",
cluster = wetland_monitoring$site,
test = "Satterthwaite"
)
Question: Why can random cross-validation be optimistic for dependent biodiversity data?
Training and test rows may share nearby years or ecological units, so a random split can evaluate an easier task than the intended application. Compare random-row, future-year and new-site holdouts; the resulting RMSE values differ because the prediction targets differ.
Keep in mind: validation should match deployment. Hold out future years for forecasting, sites for transfer to new sites, and species or clades for taxonomic transfer.
set.seed(2026)
random_test <- sample(seq_len(nrow(wetland_monitoring)),
size = floor(0.25 * nrow(wetland_monitoring)))
future_test <- wetland_monitoring$year >= 2017
site_test <- wetland_monitoring$site %in% sample(levels(wetland_monitoring$site), 3)
split_results <- list(
random_rows = list(train = !seq_len(nrow(wetland_monitoring)) %in% random_test,
test = seq_len(nrow(wetland_monitoring)) %in% random_test),
future_years = list(train = !future_test, test = future_test),
new_sites = list(train = !site_test, test = site_test)
)
cv_results <- lapply(names(split_results), function(nm) {
idx <- split_results[[nm]]
train <- wetland_monitoring[idx$train, ]
test <- wetland_monitoring[idx$test, ]
pred <- fit_lm_predict(train, test)
data.frame(
validation = nm,
n_train = nrow(train),
n_test = nrow(test),
rmse = round(rmse(test$richness, pred), 3)
)
})
knitr::kable(
do.call(rbind, cv_results),
caption = "Prediction error under random-row, future-year, and new-site validation."
)
| validation | n_train | n_test | rmse |
|---|---|---|---|
| random_rows | 180 | 60 | 2.573 |
| future_years | 192 | 48 | 2.222 |
| new_sites | 180 | 60 | 2.894 |
The prediction model contains no site-specific term. Consequently, the new-site split changes the target population but does not directly quantify leakage through a fitted site effect. The comparison is therefore an illustration of task-aligned validation; models containing site, spatial or other structured effects can show a larger contrast between random and blocked splits.
Question: Do Bayesian models remove the need to consider dependence?
No. Bayesian models can include hierarchical, temporal, spatial and
phylogenetic dependence, but the relevant structure still has to be
represented in the model. The examples below use
brms::brm() because it gives ecologists a practical formula
language for posterior uncertainty, priors and several common dependence
structures.
Keep in mind: these examples are displayed rather than
run during rendering. Bayesian fitting requires brms, Stan
tooling and deliberate checking of posterior intervals, posterior
predictive checks, convergence diagnostics and prior sensitivity.
Shown but not run by default: Bayesian examples can
take minutes to hours and require brms plus Stan tooling.
The code is visible so readers can copy and run it deliberately.
bayesian_choices <- data.frame(
"Dependence" = c(
"Hierarchical",
"Temporal",
"Spatial",
"Phylogenetic"
),
"Data clue" = c(
"Repeated observations from the same site, population or study",
"Measurements ordered through time within the same unit",
"Nearby sampling locations may be more alike than distant locations",
"Species or populations share evolutionary history"
),
"brms term" = c(
"(1 | site)",
"brms::ar(time = year, gr = site, p = 1)",
"brms::gp(easting, northing, cov = \"matern32\")",
"(1 | brms::gr(species, cov = A))"
),
"First question" = c(
"Do sites differ in their baseline richness?",
"Do neighbouring years remain similar after modelling biology?",
"Is there a smooth spatial surface in richness?",
"Are related species more similar than unrelated species?"
),
check.names = FALSE
)
knitr::kable(
bayesian_choices,
caption = "A quick map from ecological dependence questions to common brms terms."
)
| Dependence | Data clue | brms term | First question |
|---|---|---|---|
| Hierarchical | Repeated observations from the same site, population or study | (1 | site) | Do sites differ in their baseline richness? |
| Temporal | Measurements ordered through time within the same unit | brms::ar(time = year, gr = site, p = 1) | Do neighbouring years remain similar after modelling biology? |
| Spatial | Nearby sampling locations may be more alike than distant locations | brms::gp(easting, northing, cov = “matern32”) | Is there a smooth spatial surface in richness? |
| Phylogenetic | Species or populations share evolutionary history | (1 | brms::gr(species, cov = A)) | Are related species more similar than unrelated species? |
Before the model sketches, we add two small pieces of teaching data.
The spatial example uses one year of the wetland dataset and gives each
site a simple coordinate. The phylogenetic example uses a tiny
comparative dataset. In real analyses, use measured coordinates and a
published or otherwise justified tree. The wetland examples keep
family = gaussian() so the Bayesian code matches the
earlier Gaussian teaching models. Real richness, abundance and occupancy
data may instead call for Poisson, negative-binomial, hurdle,
zero-inflated, binomial or other families, checked with posterior
predictive plots.
site_coordinates <- data.frame(
site = sort(unique(wetland_monitoring$site)),
easting = c(0.0, 1.1, 2.1, 3.0, 0.4, 1.5, 2.7, 3.6, 0.2, 1.4, 2.4, 3.4),
northing = c(0.1, 0.3, 0.0, 0.4, 1.2, 1.1, 1.4, 1.0, 2.1, 2.4, 2.0, 2.3)
)
wetland_spatial <- merge(wetland_monitoring, site_coordinates, by = "site")
wetland_spatial_snapshot <- wetland_spatial[
wetland_spatial$year == max(wetland_spatial$year),
,
drop = FALSE
]
set.seed(2026)
species_names <- sprintf("sp_%02d", seq_len(24))
comparative_data <- data.frame(
species = species_names,
habitat_specialisation = runif(length(species_names), -1, 1)
)
comparative_data$body_size <- 20 +
3 * comparative_data$habitat_specialisation +
rnorm(nrow(comparative_data), 0, 2)
knitr::kable(
head(wetland_spatial_snapshot[, c("site", "year", "richness", "easting", "northing")]),
caption = "First rows of the one-year spatial snapshot used in the brms spatial sketch."
)
| site | year | richness | easting | northing | |
|---|---|---|---|---|---|
| 20 | W01 | 2020 | 25.3 | 0.0 | 0.1 |
| 40 | W02 | 2020 | 24.2 | 1.1 | 0.3 |
| 60 | W03 | 2020 | 22.4 | 2.1 | 0.0 |
| 80 | W04 | 2020 | 28.7 | 3.0 | 0.4 |
| 100 | W05 | 2020 | 24.2 | 0.4 | 1.2 |
| 120 | W06 | 2020 | 25.3 | 1.5 | 1.1 |
ggplot2::ggplot(
wetland_spatial_snapshot,
ggplot2::aes(x = easting, y = northing, colour = richness, label = site)
) +
ggplot2::geom_point(size = 3) +
ggplot2::geom_text(nudge_y = 0.12, size = 3.5, colour = "grey20") +
ggplot2::scale_colour_viridis_c(option = "D") +
ggplot2::coord_equal() +
ggplot2::labs(
x = "Simulated easting",
y = "Simulated northing",
colour = "Richness",
title = "Spatial teaching snapshot"
) +
theme_tutorial()
Teaching coordinates for the optional spatial brms example. The points are simulated site coordinates, not real mapped locations.
Question: How do we account for repeated observations from the same wetland site?
Plain-English idea: A varying intercept lets each site have its own baseline richness while sharing information across sites. This is partial pooling: site estimates are neither completely separate nor forced to be identical.
Run this code: copy the chunk below after installing
brms and a Stan backend.
After you run it, inspect: the posterior interval for
temp_anomaly and the group-level standard deviation for
site.
Interpretation: the temperature coefficient is conditional on site-level baselines. The site standard deviation describes persistent among-site heterogeneity in richness.
Next step: check posterior predictive plots and whether site-level heterogeneity is large enough to matter biologically.
Common mistake: a site random intercept is not a temporal autocorrelation term. It handles persistent site differences, not year-to-year residual memory.
set.seed(2026)
m_bayes_hierarchical <- brms::brm(
richness ~ temp_anomaly + habitat_quality + poly(year_c, 2, raw = TRUE) +
(1 | site),
data = wetland_monitoring,
family = gaussian(),
prior = c(
brms::prior(normal(0, 2), class = "b"),
brms::prior(exponential(1), class = "sd"),
brms::prior(exponential(1), class = "sigma")
),
chains = 4,
iter = 2000,
cores = 4,
seed = 2026,
control = list(adapt_delta = 0.95)
)
summary(m_bayes_hierarchical)
brms::pp_check(m_bayes_hierarchical)
Question: How do we model residual similarity among neighbouring years within each wetland?
Plain-English idea: An AR(1) term says that residuals from nearby years within the same site may be more similar than residuals far apart in time. The ecological mean model is still present; the AR term describes remaining temporal memory.
Run this code: the brms::ar() term is
placed in the formula, with time = year and gr =
site so the temporal structure applies within sites.
After you run it, inspect: the posterior for the AR parameter, the temperature effect and posterior predictive time-series checks.
Interpretation: a positive AR parameter means that years close together remain similar after the model accounts for temperature, habitat, year trend and site baseline.
Next step: compare posterior predictive behaviour through time, not just coefficient intervals.
Common mistake: do not use an AR term to hide an omitted ecological trend or missing covariate.
m_bayes_temporal <- brms::brm(
brms::bf(
richness ~ temp_anomaly + habitat_quality + poly(year_c, 2, raw = TRUE) +
(1 | site) + brms::ar(time = year, gr = site, p = 1)
),
data = wetland_monitoring,
family = gaussian(),
prior = c(
brms::prior(normal(0, 2), class = "b"),
brms::prior(exponential(1), class = "sd"),
brms::prior(exponential(1), class = "sigma"),
brms::prior(normal(0, 0.5), class = "ar")
),
chains = 4,
iter = 2000,
cores = 4,
seed = 2026,
control = list(adapt_delta = 0.95)
)
summary(m_bayes_temporal)
brms::pp_check(m_bayes_temporal)
Question: How do we allow nearby wetland sites to have similar richness?
Plain-English idea: A Gaussian process is a smooth spatial surface. Sites close together can share information, and the model estimates how quickly similarity decays with distance.
Run this code: this sketch uses one year of data so that the spatial example is not mixed with the temporal example. In a real monitoring study, repeated years may require site-level and temporal terms as well.
After you run it, inspect: the GP standard deviation
and length-scale. The standard deviation tells you the size of the
spatial surface; the length-scale describes spatial range on the scale
used by the GP predictors, so check the brms output and
documentation before translating it back to metres or kilometres.
Interpretation: spatial structure is not just a prettier map. It changes the target from independent site observations to a spatially structured ecological field.
Next step: check whether coordinates, projection, boundaries and sampling scale make a smooth GP sensible.
Common mistake: do not treat arbitrary row order or site labels as coordinates. Spatial dependence needs actual spatial information.
m_bayes_spatial <- brms::brm(
richness ~ temp_anomaly + habitat_quality +
brms::gp(easting, northing, cov = "matern32"),
data = wetland_spatial_snapshot,
family = gaussian(),
prior = c(
brms::prior(normal(0, 2), class = "b"),
brms::prior(exponential(1), class = "sigma"),
brms::prior(exponential(1), class = "sdgp")
),
chains = 4,
iter = 2000,
cores = 4,
seed = 2026,
control = list(adapt_delta = 0.95)
)
summary(m_bayes_spatial)
brms::conditional_effects(m_bayes_spatial)
brms::pp_check(m_bayes_spatial)
Before changing GP priors, run:
brms::get_prior(
richness ~ temp_anomaly + habitat_quality +
brms::gp(easting, northing, cov = "matern32"),
data = wetland_spatial_snapshot,
family = gaussian()
)
This is a teaching sketch with 12 simulated site coordinates. It is useful for learning the syntax, but not enough by itself to support a strong spatial inference claim. A real spatial analysis should check sample size, coordinate projection, boundary effects, anisotropy, nonstationarity and whether a smooth surface matches the sampling design.
Question: How do we account for related species being more similar than unrelated species?
Plain-English idea: A phylogenetic model uses a
covariance matrix derived from a tree. In brms, the matrix
is passed through data2 and used with
brms::gr(species, cov = A).
Run this code: the example simulates a tiny tree only for teaching. Replace it with the tree and species names justified for your analysis.
After you run it, inspect: the phylogenetic group-level standard deviation and the posterior interval for the ecological predictor.
Interpretation: the model asks whether the predictor explains trait differences after allowing related species to share evolutionary history.
Next step: check species names, tree pruning, covariance scaling and prior sensitivity.
Common mistake: do not pass a tree whose tip labels do not match the species column. The covariance matrix row names must correspond to the grouping levels.
library(ape)
tree <- ape::rtree(
n = length(species_names),
tip.label = species_names
)
A <- ape::vcv.phylo(tree, corr = TRUE)
m_bayes_phylogenetic <- brms::brm(
body_size ~ habitat_specialisation +
(1 | brms::gr(species, cov = A)),
data = comparative_data,
data2 = list(A = A),
family = gaussian(),
prior = c(
brms::prior(normal(0, 2), class = "b"),
brms::prior(exponential(1), class = "sd"),
brms::prior(exponential(1), class = "sigma")
),
chains = 4,
iter = 2000,
cores = 4,
seed = 2026,
control = list(adapt_delta = 0.95)
)
summary(m_bayes_phylogenetic)
brms::pp_check(m_bayes_phylogenetic)
Question: What should I check after a Bayesian model finishes?
Plain-English idea: Bayesian output is not a single coefficient table. You need to check computation, posterior uncertainty and whether simulated data from the model resemble the observed data.
Run this code: replace m_bayes_temporal
with whichever fitted model you are checking.
After you run it, inspect: Rhat,
Bulk_ESS, Tail_ESS, divergent-transition
warnings, trace plots, posterior predictive checks, posterior intervals
and loo() diagnostics if models are compared.
Interpretation: a clean posterior workflow supports interpretation; it does not rescue a model with the wrong dependence structure or a mismatched validation design.
Next step: report priors, diagnostics, software versions and sensitivity checks.
Common mistake: do not report only posterior means. Intervals, predictive checks and convergence diagnostics are part of the result.
summary(m_bayes_temporal)
plot(m_bayes_temporal)
brms::pp_check(m_bayes_temporal)
brms::conditional_effects(m_bayes_temporal)
brms::loo(m_bayes_temporal)
Use this mini-rubric when reading the output:
summary(), find
Rhat, Bulk_ESS and Tail_ESS.
Values of Rhat close to 1 and reasonably large effective
sample sizes support stable posterior summaries.plot(model), chains
should mix rather than form separated bands, long drifts or stuck
segments.pp_check(model), simulated data should resemble the
observed data in features that matter for the question, such as spread,
tails, zeros or temporal pattern.loo(model), inspect Pareto-k warnings before
trusting expected log predictive density differences.If Stan reports divergent transitions after warmup, treat that as a
diagnostic warning rather than a harmless message. Reconsider scaling,
priors, model complexity and sampler controls such as
adapt_delta. If a model becomes very slow, first fit a
simpler version and confirm that the ecological question still requires
the more complex dependence structure.
The core examples teach the workflow. The next panels help readers choose the right next tool when their data have stronger structure than this tutorial can fit in a short web page.
Use these when observations are linked by geographic distance or
spatial fields. Packages include sdmTMB, INLA,
spaMM, and glmmTMB.
mesh <- sdmTMB::make_mesh(dat, xy_cols = c("x", "y"), cutoff = 10)
m_spatial <- sdmTMB::sdmTMB(
count ~ habitat + depth,
data = dat,
mesh = mesh,
family = nbinom2(),
spatial = "on",
spatiotemporal = "ar1",
time = "year"
)
Caveat: distance-based spatial models often assume a particular covariance shape. Check stationarity, anisotropy, boundaries, and the scale of sampling.
Use these for rivers and streams where flow connectivity matters. Stream sites can be close in Euclidean distance but disconnected by flow.
m_stream <- SSN2::ssn_lm(
richness ~ temperature + canopy,
ssn.object = stream_network_object,
tailup_type = "exponential",
additive = "afvArea"
)
Caveat: this is not ordinary two-dimensional spatial autocorrelation. Directional flow and branching structure are part of the model.
Use these when dependence is defined by neighbours among areas, polygons, or network nodes rather than by continuous distance.
m_bym2 <- INLA::inla(
count ~ habitat + f(area_id, model = "bym2", graph = adjacency_graph),
family = "poisson",
data = area_data
)
Caveat: adjacency models answer an areal-neighbour question. They are not automatically appropriate for point-referenced observations.
Use these when species share evolutionary history.
A <- ape::vcv.phylo(tree, corr = TRUE)
m_phylo <- brms::brm(
trait ~ environment + (1 | brms::gr(species, cov = A)),
data = trait_data,
data2 = list(A = A),
family = gaussian()
)
Caveat: the tree, branch lengths, and evolutionary model are assumptions, not decoration.
Use these when many species are modelled together and residual association among species is part of the question.
m_gllvm <- gllvm::gllvm(
y = species_matrix,
X = environmental_data,
family = "negative.binomial",
num.lv = 2,
method = "VA"
)
Caveat: latent variables can reveal residual structure, but they need careful interpretation and diagnostics.
Use these when the dataset is too large for dense covariance matrices or needs spatio-temporal prediction.
m_frk <- FRK::SRE(
f = z ~ covariate,
data = spatial_data,
basis = FRK::auto_basis(manifold = FRK::plane(), data = spatial_data)
)
Caveat: reduced-rank or basis-function models trade exact covariance detail for scalability and prediction.
Use these when the covariance among levels is known or estimated from pedigree, genomic, or other relationship matrices.
m_sommer <- sommer::mmer(
trait ~ environment,
random = ~ sommer::vsr(species, Gu = relationship_matrix),
data = trait_data
)
Caveat: dense covariance problems can become computationally difficult, and the relationship matrix must be biologically defensible.
These tables are a map, not a ranking. Beginner suitability refers to first use by an applied ecologist, not to the quality of the package. The information is split into narrower tables so it is easier to read on small screens and with screen readers.
Start here before reading the tables:
lme4, glmmTMB, or
nlme.nlme::gls() and corAR1().glmmTMB, then add structure cautiously.geepack, but state that the estimand is marginal.link <- function(text, url) {
sprintf("<a href='%s'>%s</a>", url, text)
}
pkg_matrix <- data.frame(
problem = c(
"Gaussian repeated measures", "GLMMs and covariance structures",
"Hierarchical LMMs/GLMMs", "Bayesian multilevel dependence",
"Marginal correlated data", "Within-unit panel effects",
"Robust covariance", "Cluster-robust small-sample inference",
"Simulation residual diagnostics", "Smooth temporal/spatial signal",
"Stream-network dependence", "Spatial/spatio-temporal GLMMs",
"Large spatial/spatio-temporal prediction", "Latent Gaussian Bayesian models",
"Community/JSDM ordination", "Survey/spatio-temporal multivariate models",
"Spatial GLMMs", "Known relationship matrices"
),
package = c(
"nlme", "glmmTMB", "lme4", "brms", "geepack", "plm", "sandwich",
"clubSandwich", "DHARMa", "mgcv", "SSN2", "sdmTMB", "FRK", "INLA",
"gllvm", "VAST/tinyVAST", "spaMM", "sommer"
),
core_or_extension = c(
"core", "core", "extension", "extension", "extension", "extension",
"core", "extension", "extension", "extension", "extension", "extension",
"extension", "extension", "extension", "extension", "extension",
"extension"
),
estimand = c(
"model-based conditional/GLS", "conditional", "conditional",
"posterior conditional or marginal contrasts", "marginal",
"within-unit", "same coefficient, adjusted SE",
"same coefficient, adjusted SE", "diagnostic, not estimand",
"smooth systematic component", "model-based stream-network effect",
"spatial/spatio-temporal conditional", "prediction and latent field",
"Bayesian latent Gaussian", "latent-variable community response",
"spatio-temporal density or multivariate response", "conditional",
"mixed-model effects with known covariance"
),
temporal = c(
"yes", "yes", "limited directly", "yes", "working correlation",
"panel time", "via clusters", "via clusters", "yes diagnostics",
"smooths and GAMM tools", "not main target", "yes", "yes", "yes",
"indirect", "yes", "yes", "possible"
),
spatial = c(
"yes for selected corStruct", "yes covariance structures",
"via grouping, not geostatistical by default", "GP/CAR/SAR options",
"via clusters, not spatial field", "panel units", "via clusters",
"via clusters", "spatial diagnostic", "smooth spatial terms",
"stream networks", "yes", "yes", "yes", "latent structure",
"yes", "yes", "possible with covariance"
),
non_gaussian = c(
"mostly no", "yes", "yes", "yes", "yes", "mostly linear",
"depends on fitted model", "depends on fitted model", "yes diagnostics",
"yes", "some support", "yes", "yes in recent FRK", "yes", "yes",
"yes", "yes", "mostly linear/mixed"
),
beginner_suitability = c(
"medium", "medium", "high for random effects", "medium-low", "medium",
"medium", "medium", "medium", "high for diagnostics", "medium",
"medium-low", "medium", "medium-low", "low", "medium", "low",
"medium-low", "medium-low"
),
caveat = c(
"Gaussian focus; formula details matter",
"covariance syntax must match data spacing and grouping",
"does not directly fit residual AR(1) the way nlme does",
"requires priors and MCMC diagnostics",
"working correlation is not a mechanistic covariance model",
"linear panel framing; estimand differs from random effects",
"adjusts SE, not the model",
"cluster count and correction matter",
"diagnostics depend on correct simulation setup",
"smooths can model signal, not necessarily residual covariance",
"requires stream-network data objects",
"mesh/SPDE choices matter",
"basis choice and support matter",
"powerful but steep learning curve",
"latent variables need ecological interpretation",
"specialized for survey and multivariate spatio-temporal use",
"specialized syntax and assumptions",
"dense covariance and p > n settings need care"
),
verified_source = c(
link("nlme manual", "https://cran.r-project.org/web/packages/nlme/nlme.pdf"),
link("glmmTMB covariance vignette", "https://cran.r-project.org/package%3DglmmTMB/vignettes/covstruct.html"),
link("lme4 CRAN", "https://cran.r-project.org/package%3Dlme4"),
link("brms AR docs", "https://paulbuerkner.com/brms/reference/ar.html"),
link("geepack manual", "https://cran.r-project.org/web/packages/geepack/refman/geepack.html"),
link("plm CRAN", "https://cran.r-project.org/package%3Dplm"),
link("sandwich vcovCL", "https://sandwich.r-forge.r-project.org/reference/vcovCL.html"),
link("clubSandwich vcovCR", "https://jepusto.github.io/clubSandwich/reference/vcovCR.html"),
link("DHARMa vignette", "https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html"),
link("mgcv CRAN", "https://cran.r-project.org/package%3Dmgcv"),
link("SSN2 docs", "https://usepa.github.io/SSN2/"),
link("sdmTMB docs", "https://sdmtmb.github.io/sdmTMB/"),
link("FRK JSS", "https://www.jstatsoft.org/article/view/v098i04"),
link("R-INLA latent models", "https://sites.google.com/a/r-inla.org/www/models/latent-models"),
link("gllvm docs", "https://jenniniku.github.io/gllvm/"),
link("tinyVAST CRAN", "https://cran.r-project.org/package%3DtinyVAST"),
link("spaMM CRAN", "https://cran.r-project.org/package%3DspaMM"),
link("sommer CRAN", "https://cran.r-project.org/package%3Dsommer")
)
)
pkg_orientation <- pkg_matrix[, c(
"problem", "package", "core_or_extension", "estimand", "beginner_suitability"
)]
pkg_capabilities <- pkg_matrix[, c(
"package", "temporal", "spatial", "non_gaussian", "caveat", "verified_source"
)]
knitr::kable(
pkg_orientation,
escape = FALSE,
caption = "Package orientation: what problem each package is commonly used for and what estimand it tends to target."
)
| problem | package | core_or_extension | estimand | beginner_suitability |
|---|---|---|---|---|
| Gaussian repeated measures | nlme | core | model-based conditional/GLS | medium |
| GLMMs and covariance structures | glmmTMB | core | conditional | medium |
| Hierarchical LMMs/GLMMs | lme4 | extension | conditional | high for random effects |
| Bayesian multilevel dependence | brms | extension | posterior conditional or marginal contrasts | medium-low |
| Marginal correlated data | geepack | extension | marginal | medium |
| Within-unit panel effects | plm | extension | within-unit | medium |
| Robust covariance | sandwich | core | same coefficient, adjusted SE | medium |
| Cluster-robust small-sample inference | clubSandwich | extension | same coefficient, adjusted SE | medium |
| Simulation residual diagnostics | DHARMa | extension | diagnostic, not estimand | high for diagnostics |
| Smooth temporal/spatial signal | mgcv | extension | smooth systematic component | medium |
| Stream-network dependence | SSN2 | extension | model-based stream-network effect | medium-low |
| Spatial/spatio-temporal GLMMs | sdmTMB | extension | spatial/spatio-temporal conditional | medium |
| Large spatial/spatio-temporal prediction | FRK | extension | prediction and latent field | medium-low |
| Latent Gaussian Bayesian models | INLA | extension | Bayesian latent Gaussian | low |
| Community/JSDM ordination | gllvm | extension | latent-variable community response | medium |
| Survey/spatio-temporal multivariate models | VAST/tinyVAST | extension | spatio-temporal density or multivariate response | low |
| Spatial GLMMs | spaMM | extension | conditional | medium-low |
| Known relationship matrices | sommer | extension | mixed-model effects with known covariance | medium-low |
knitr::kable(
pkg_capabilities,
escape = FALSE,
caption = "Package capabilities and caveats. Use this table after choosing the scientific question."
)
| package | temporal | spatial | non_gaussian | caveat | verified_source |
|---|---|---|---|---|---|
| nlme | yes | yes for selected corStruct | mostly no | Gaussian focus; formula details matter | nlme manual |
| glmmTMB | yes | yes covariance structures | yes | covariance syntax must match data spacing and grouping | glmmTMB covariance vignette |
| lme4 | limited directly | via grouping, not geostatistical by default | yes | does not directly fit residual AR(1) the way nlme does | lme4 CRAN |
| brms | yes | GP/CAR/SAR options | yes | requires priors and MCMC diagnostics | brms AR docs |
| geepack | working correlation | via clusters, not spatial field | yes | working correlation is not a mechanistic covariance model | geepack manual |
| plm | panel time | panel units | mostly linear | linear panel framing; estimand differs from random effects | plm CRAN |
| sandwich | via clusters | via clusters | depends on fitted model | adjusts SE, not the model | sandwich vcovCL |
| clubSandwich | via clusters | via clusters | depends on fitted model | cluster count and correction matter | clubSandwich vcovCR |
| DHARMa | yes diagnostics | spatial diagnostic | yes diagnostics | diagnostics depend on correct simulation setup | DHARMa vignette |
| mgcv | smooths and GAMM tools | smooth spatial terms | yes | smooths can model signal, not necessarily residual covariance | mgcv CRAN |
| SSN2 | not main target | stream networks | some support | requires stream-network data objects | SSN2 docs |
| sdmTMB | yes | yes | yes | mesh/SPDE choices matter | sdmTMB docs |
| FRK | yes | yes | yes in recent FRK | basis choice and support matter | FRK JSS |
| INLA | yes | yes | yes | powerful but steep learning curve | R-INLA latent models |
| gllvm | indirect | latent structure | yes | latent variables need ecological interpretation | gllvm docs |
| VAST/tinyVAST | yes | yes | yes | specialized for survey and multivariate spatio-temporal use | tinyVAST CRAN |
| spaMM | yes | yes | yes | specialized syntax and assumptions | spaMM CRAN |
| sommer | possible | possible with covariance | mostly linear/mixed | dense covariance and p > n settings need care | sommer CRAN |
Copy this checklist into the analysis supplement, lab notebook, or review response.
if (has_pkg("sessioninfo")) {
sessioninfo::session_info()
} else {
sessionInfo()
}
#> ─ Session info ───────────────────────────────────────────────────────────────
#> setting value
#> version R version 4.6.0 (2026-04-24)
#> os macOS Tahoe 26.6
#> system aarch64, darwin23
#> ui X11
#> language (EN)
#> collate C.UTF-8
#> ctype C.UTF-8
#> tz America/Edmonton
#> date 2026-08-12
#> pandoc 3.9.0.2 @ /opt/homebrew/bin/ (via rmarkdown)
#> quarto NA
#>
#> ─ Packages ───────────────────────────────────────────────────────────────────
#> package * version date (UTC) lib source
#> abind 1.4-8 2024-09-12 [1] CRAN (R 4.6.0)
#> ape 5.8-1 2024-12-16 [1] CRAN (R 4.6.0)
#> backports 1.5.1 2026-04-03 [1] CRAN (R 4.6.0)
#> bayesplot 1.15.0 2025-12-12 [1] CRAN (R 4.6.0)
#> boot 1.3-32 2025-08-29 [2] CRAN (R 4.6.0)
#> bridgesampling 1.2-1 2025-11-19 [1] CRAN (R 4.6.0)
#> brms 2.23.0 2025-09-09 [1] CRAN (R 4.6.0)
#> Brobdingnag 1.2-9 2022-10-19 [1] CRAN (R 4.6.0)
#> bslib 0.11.0 2026-05-16 [1] CRAN (R 4.6.0)
#> cachem 1.1.0 2024-05-16 [1] CRAN (R 4.6.0)
#> checkmate 2.3.4 2026-02-03 [1] CRAN (R 4.6.0)
#> cli 3.6.6 2026-04-09 [1] CRAN (R 4.6.0)
#> coda 0.19-4.1 2024-01-31 [1] CRAN (R 4.6.0)
#> codetools 0.2-20 2024-03-31 [2] CRAN (R 4.6.0)
#> DHARMa 0.5.0 2026-06-01 [1] CRAN (R 4.6.0)
#> digest 0.6.39 2025-11-19 [1] CRAN (R 4.6.0)
#> distributional 0.8.1 2026-06-27 [1] CRAN (R 4.6.1)
#> doParallel 1.0.17 2022-02-07 [1] CRAN (R 4.6.0)
#> dplyr 1.2.1 2026-04-03 [1] CRAN (R 4.6.0)
#> emmeans 2.0.3 2026-04-09 [1] CRAN (R 4.6.0)
#> estimability 2.0.0 2026-06-26 [1] CRAN (R 4.6.1)
#> evaluate 1.0.5 2025-08-27 [1] CRAN (R 4.6.0)
#> farver 2.1.2 2024-05-13 [1] CRAN (R 4.6.0)
#> fastmap 1.2.0 2024-05-15 [1] CRAN (R 4.6.0)
#> foreach 1.5.2 2022-02-02 [1] CRAN (R 4.6.0)
#> gap 1.15.2 2026-05-28 [1] CRAN (R 4.6.0)
#> gap.datasets 0.0.6 2023-08-25 [1] CRAN (R 4.6.0)
#> generics 0.1.4 2025-05-09 [1] CRAN (R 4.6.0)
#> ggplot2 4.0.3 2026-04-22 [1] CRAN (R 4.6.0)
#> glmmTMB 1.1.14 2026-01-15 [1] CRAN (R 4.6.0)
#> glue 1.8.1 2026-04-17 [1] CRAN (R 4.6.0)
#> gtable 0.3.6 2024-10-25 [1] CRAN (R 4.6.0)
#> htmltools 0.5.9 2025-12-04 [1] CRAN (R 4.6.0)
#> httpuv 1.6.17 2026-03-18 [1] CRAN (R 4.6.0)
#> iterators 1.0.14 2022-02-05 [1] CRAN (R 4.6.0)
#> jquerylib 0.1.4 2021-04-26 [1] CRAN (R 4.6.0)
#> jsonlite 2.0.0 2025-03-27 [1] CRAN (R 4.6.0)
#> knitr 1.51 2025-12-20 [1] CRAN (R 4.6.0)
#> labeling 0.4.3 2023-08-29 [1] CRAN (R 4.6.0)
#> later 1.4.8 2026-03-05 [1] CRAN (R 4.6.0)
#> lattice 0.22-9 2026-02-09 [2] CRAN (R 4.6.0)
#> lifecycle 1.0.5 2026-01-08 [1] CRAN (R 4.6.0)
#> lme4 2.0-1 2026-03-05 [1] CRAN (R 4.6.0)
#> lmtest 0.9-40 2022-03-21 [1] CRAN (R 4.6.0)
#> loo 2.10.1 2026-07-24 [1] CRAN (R 4.6.1)
#> magrittr 2.0.5 2026-04-04 [1] CRAN (R 4.6.0)
#> MASS 7.3-65 2025-02-28 [2] CRAN (R 4.6.0)
#> Matrix 1.7-5 2026-03-21 [2] CRAN (R 4.6.0)
#> matrixStats 1.5.0 2025-01-07 [1] CRAN (R 4.6.0)
#> mgcv 1.9-4 2025-11-07 [2] CRAN (R 4.6.0)
#> mime 0.13 2025-03-17 [1] CRAN (R 4.6.0)
#> minqa 1.2.8 2024-08-17 [1] CRAN (R 4.6.0)
#> multcomp 1.4-31 2026-07-12 [1] CRAN (R 4.6.1)
#> mvtnorm 1.4-1 2026-06-06 [1] CRAN (R 4.6.0)
#> nlme 3.1-169 2026-03-27 [2] CRAN (R 4.6.0)
#> nloptr 2.2.1 2025-03-17 [1] CRAN (R 4.6.0)
#> numDeriv 2016.8-1.1 2019-06-06 [1] CRAN (R 4.6.0)
#> otel 0.2.0 2025-08-29 [1] CRAN (R 4.6.0)
#> pillar 1.11.1 2025-09-17 [1] CRAN (R 4.6.0)
#> pkgconfig 2.0.3 2019-09-22 [1] CRAN (R 4.6.0)
#> plyr 1.8.9 2023-10-02 [1] CRAN (R 4.6.0)
#> posterior 1.7.0 2026-04-01 [1] CRAN (R 4.6.0)
#> promises 1.5.0 2025-11-01 [1] CRAN (R 4.6.0)
#> qgam 2.0.0 2025-04-10 [1] CRAN (R 4.6.0)
#> R6 2.6.1 2025-02-15 [1] CRAN (R 4.6.0)
#> rbibutils 2.4.1 2026-01-21 [1] CRAN (R 4.6.0)
#> RColorBrewer 1.1-3 2022-04-03 [1] CRAN (R 4.6.0)
#> Rcpp 1.1.1-1.1 2026-04-24 [1] CRAN (R 4.6.0)
#> RcppParallel 5.1.11-2 2026-03-05 [1] CRAN (R 4.6.0)
#> Rdpack 2.6.6 2026-02-08 [1] CRAN (R 4.6.0)
#> reformulas 0.4.4 2026-02-02 [1] CRAN (R 4.6.0)
#> rlang 1.2.0 2026-04-06 [1] CRAN (R 4.6.0)
#> rmarkdown 2.31 2026-03-26 [1] CRAN (R 4.6.0)
#> rstantools 2.7.0 2026-07-26 [1] CRAN (R 4.6.1)
#> S7 0.2.2 2026-04-22 [1] CRAN (R 4.6.0)
#> sandwich 3.1-1 2024-09-15 [1] CRAN (R 4.6.0)
#> sass 0.4.10 2025-04-11 [1] CRAN (R 4.6.0)
#> scales 1.4.0 2025-04-24 [1] CRAN (R 4.6.0)
#> sessioninfo 1.2.4 2026-06-04 [1] CRAN (R 4.6.0)
#> shiny 1.14.0 2026-06-21 [1] CRAN (R 4.6.0)
#> stringi 1.8.7 2025-03-27 [1] CRAN (R 4.6.0)
#> stringr 1.6.0 2025-11-04 [1] CRAN (R 4.6.0)
#> survival 3.8-6 2026-01-16 [2] CRAN (R 4.6.0)
#> tensorA 0.36.2.1 2023-12-13 [1] CRAN (R 4.6.0)
#> TH.data 1.1-5 2025-11-17 [1] CRAN (R 4.6.0)
#> tibble 3.3.1 2026-01-11 [1] CRAN (R 4.6.0)
#> tidyselect 1.2.1 2024-03-11 [1] CRAN (R 4.6.0)
#> TMB 1.9.21 2026-03-23 [1] CRAN (R 4.6.0)
#> vctrs 0.7.3 2026-04-11 [1] CRAN (R 4.6.0)
#> viridisLite 0.4.3 2026-02-04 [1] CRAN (R 4.6.0)
#> withr 3.0.3 2026-06-19 [1] CRAN (R 4.6.0)
#> xfun 0.59 2026-06-19 [1] CRAN (R 4.6.0)
#> xtable 1.8-8 2026-02-22 [1] CRAN (R 4.6.0)
#> yaml 2.3.12 2025-12-10 [1] CRAN (R 4.6.0)
#> zoo 1.8-15 2025-12-15 [1] CRAN (R 4.6.0)
#>
#> [1] /Users/z3437171/Library/R/arm64/4.6/library
#> [2] /Library/Frameworks/R.framework/Versions/4.6/Resources/library
#>
#> ──────────────────────────────────────────────────────────────────────────────