Introduction
This tutorial has two parts. The first summarizes diagnostic tools for detecting residual dependence and other common departures from model assumptions. The second uses a simulated time series to demonstrate a principled modelling workflow: represent plausible ecological trends first, diagnose the dependence that remains, and add a residual dependence structure when it is needed.
1 Model diagnostics
Model diagnostics ask whether the residuals behave as expected under the fitted model. The relevant target is therefore residual dependence, conditional on the systematic component and all other structures already represented in the model, rather than patterning in the observed response itself.
DHARMa provides simulation-based residual diagnostics for many
generalized linear and mixed-effects models. After creating a DHARMa
residual object with simulateResiduals(), the following
tools can be used as part of a broader diagnostic assessment.
| Diagnostic question | Useful DHARMa tools | Interpretation |
|---|---|---|
| Is temporal structure left in the residuals? | testTemporalAutocorrelation(res, time = ...) |
Tests whether residuals remain autocorrelated over time. |
| Is spatial structure left in the residuals? | testSpatialAutocorrelation(res, x = ..., y = ...)
or a distance matrix |
Tests whether residual similarity varies with spatial distance. |
| Is phylogenetic structure left in the residuals? | testPhylogeneticAutocorrelation(res, tree = ...) |
Tests whether residual similarity follows phylogenetic relatedness. |
| Is the response more or less variable than expected under the model? | testDispersion(res) |
Assesses overdispersion or underdispersion relative to model-based simulations. |
| Does residual spread vary across fitted values, predictors or groups? | plotResiduals(res, predictor) and other
residual plots |
Systematic changes in residual spread can indicate heteroscedasticity. |
| Are there more extreme observations than the fitted model predicts? | plot(res, quantreg = TRUE) and
testOutliers(res) |
Identifies observations outside the simulation envelope more often than expected. |
These procedures answer different questions. In particular,
testDispersion() is not a specific test of
heteroscedasticity: dispersion concerns overall variability relative to
the fitted distribution, whereas heteroscedasticity concerns changes in
residual variance across the predictor space. Both graphical and
numerical diagnostics should therefore be considered.
Temporal tests require unique time values, and spatial tests require
unique coordinates. With repeated observations at the same time or
location, residuals may need to be aggregated using
recalculateResiduals() or examined separately within the
relevant series or strata. Diagnostics also depend on how simulations
are generated. For models containing explicit temporal, spatial or
phylogenetic correlation structures, conditional simulations, residual
rotation or a custom comparison of observed and simulated correlation
may sometimes be required.
Diagnostic P values should not be used as binary decision rules. They are indicators of possible model misspecification and should be interpreted alongside residual plots, the direction and magnitude of deviations, sample size, and ecological plausibility. A small P value does not identify the source of a problem, and a large P value does not demonstrate that the model is adequate.
The worked example below focuses on temporal dependence. The same principle applies to spatial and phylogenetic data: first specify the ecological processes that shape the expected response, and then use the appropriate coordinates, distance matrix or phylogenetic tree to assess the structure remaining in the residuals.
2 Correct modelling workflow for dependent data
For deciding whether an additional dependence structure is required, the relevant quantity is the residual dependence remaining after the systematic component and other model structures have been represented. Spatial, temporal or phylogenetic patterns in the observed response do not, by themselves, demonstrate residual autocorrelation. Such patterns may arise because the expected response varies systematically with environmental conditions, time, space or evolutionary history. Researchers should therefore represent plausible ecological trends using appropriate covariates, interactions or smooth functions before diagnosing any residual dependence that remains.
A defensible workflow is to specify the systematic component from ecological knowledge, fit the model, simulate and inspect residuals, test for residual dependence, revise the dependence structure if necessary, and then repeat the diagnostics. The following example isolates these steps using temporal data.
2.2 Begin with a model that omits the systematic ecological component
We begin with an intercept-only model that omits temperature. Its residuals therefore contain both the unexplained temperature effect and the temporal dependence introduced during simulation. This deliberately misspecified model provides a useful diagnostic baseline.
ignore_trend = lm(richness ~ 1, data = temporal_data)
summary(ignore_trend)
##
## Call:
## lm(formula = richness ~ 1, data = temporal_data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -8.8622 -1.5247 0.0568 1.4462 7.2554
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 19.92457 0.07224 275.8 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.284 on 999 degrees of freedom
We first inspect the residuals in observation order.
plot(residuals(ignore_trend))
The autocorrelation function (ACF), partial autocorrelation function
(PACF) and DHARMa temporal test provide complementary views
of residual association across temporal lags.
library(DHARMa)
## This is DHARMa 0.4.7. For overview type '?DHARMa'. For recent changes, type news(package = 'DHARMa')
acf(residuals(ignore_trend), type = "correlation", plot = T)
pacf(residuals(ignore_trend), plot = T)
testTemporalAutocorrelation(ignore_trend, time = temporal_data$year)
##
## Durbin-Watson test
##
## data: simulationOutput$scaledResiduals ~ 1
## DW = 1.6459, p-value = 2.097e-08
## alternative hypothesis: true autocorrelation is not 0
2.3 Represent the systematic component before modelling dependence
We next include temperature in the systematic component but continue to assume independent residuals. This separates the environmental association of interest from any temporal dependence that remains.
mod_trend = lm(richness ~ temperature, data = temporal_data)
summary(mod_trend)
##
## Call:
## lm(formula = richness ~ temperature, data = temporal_data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.7551 -0.7502 -0.0138 0.8451 3.2166
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 19.92457 0.03576 557.19 <2e-16 ***
## temperature 1.98520 0.03578 55.49 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.131 on 998 degrees of freedom
## Multiple R-squared: 0.7552, Adjusted R-squared: 0.755
## F-statistic: 3079 on 1 and 998 DF, p-value: < 2.2e-16
The same systematic component can be fitted using generalized least
squares. At this stage, no correlation structure has been specified, so
mod_trend2 remains an independence model.
library(nlme)
mod_trend2 <- gls(
richness ~ temperature,
data = temporal_data
)
summary(mod_trend2)
## Generalized least squares fit by REML
## Model: richness ~ temperature
## Data: temporal_data
## AIC BIC logLik
## 3097.383 3112.1 -1545.692
##
## Coefficients:
## Value Std.Error t-value p-value
## (Intercept) 19.924571 0.03575918 557.1875 0
## temperature 1.985204 0.03577708 55.4882 0
##
## Correlation:
## (Intr)
## temperature 0
##
## Standardized residuals:
## Min Q1 Med Q3 Max
## -3.32075490 -0.66340322 -0.01220586 0.74737457 2.84455330
##
## Residual standard error: 1.130805
## Degrees of freedom: 1000 total; 998 residual
For comparison, mod_trend3 represents temporal
dependence but omits temperature. The constant grouping factor denotes a
single time series; with multiple series it should be replaced by the
corresponding grouping variable.
library(glmmTMB)
## Warning: package 'glmmTMB' was built under R version 4.0.5
## Warning in checkDepPackageVersion(dep_pkg = "TMB"): Package version inconsistency detected.
## glmmTMB was built with TMB version 1.8.1
## Current TMB version is 1.9.14
## Please re-install glmmTMB from source or restore original 'TMB' package (see '?reinstalling' for more information)
mod_trend3 = glmmTMB(richness ~ ar1(factor(year) + 0 | 1), data = temporal_data) # `1` can be replaced by `grp` indicating multiple time series
summary(mod_trend3)
## Family: gaussian ( identity )
## Formula: richness ~ ar1(factor(year) + 0 | 1)
## Data: temporal_data
##
## AIC BIC logLik deviance df.resid
## 4493.1 4502.9 -2244.5 4489.1 998
##
##
## Dispersion estimate for gaussian family (sigma^2): 5.21
##
## Conditional model:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 19.9246 0.0722 275.9 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
testTemporalAutocorrelation(mod_trend3, time = temporal_data$year)
##
## Durbin-Watson test
##
## data: simulationOutput$scaledResiduals ~ 1
## DW = 1.646, p-value = 2.107e-08
## alternative hypothesis: true autocorrelation is not 0
Finally, we fit models that represent both the systematic temperature effect and AR(1) temporal dependence. This is the data-generating structure used in the simulation.
# using gls
mod_trend4 <- gls(
richness ~ temperature,
corr = corAR1(0.9, form = ~ 1),
data = temporal_data
)
summary(mod_trend4)
## Generalized least squares fit by REML
## Model: richness ~ temperature
## Data: temporal_data
## AIC BIC logLik
## 1399.057 1418.68 -695.5287
##
## Correlation Structure: AR(1)
## Formula: ~1
## Parameter estimate(s):
## Phi
## 0.9055215
##
## Coefficients:
## Value Std.Error t-value p-value
## (Intercept) 19.928897 0.1601353 124.4504 0
## temperature 1.988704 0.0112399 176.9326 0
##
## Correlation:
## (Intr)
## temperature -0.002
##
## Standardized residuals:
## Min Q1 Med Q3 Max
## -3.30588263 -0.66366522 -0.01672808 0.74095528 2.81994165
##
## Residual standard error: 1.138332
## Degrees of freedom: 1000 total; 998 residual
#using glmmTMB
mod_trend5 = glmmTMB(richness ~ temperature + ar1(0 + factor(year) | 1), data = temporal_data)
summary(mod_trend5)
## Family: gaussian ( identity )
## Formula: richness ~ temperature + ar1(0 + factor(year) | 1)
## Data: temporal_data
##
## AIC BIC logLik deviance df.resid
## 3087.7 3102.5 -1540.9 3081.7 997
##
##
## Dispersion estimate for gaussian family (sigma^2): 1.28
##
## Conditional model:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 19.92457 0.03572 557.7 <2e-16 ***
## temperature 1.98520 0.03574 55.5 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
2.4 Compare residual diagnostics across candidate models
The diagnostic plots assess whether residuals behave as expected under each fitted model. We look for:
uniform residual distribution
no strong structure in residual plots
no systematic trends
Persistent temporal autocorrelation appears as systematic association among residuals ordered through time. Comparing the models helps distinguish inadequate representation of the systematic component from inadequate representation of residual dependence.
First, we diagnose the model that includes temperature but assumes
independent residuals (mod_trend).
acf(residuals(mod_trend), type = "correlation", plot = T)
pacf(residuals(mod_trend), plot = T)
#library(DHARMa)
res <- simulateResiduals(mod_trend)
plot(res)
## Warning in newton(lsp = lsp, X = G$X, y = G$y, Eb = G$Eb, UrS = G$UrS, L =
## G$L, : Fitting terminated with step failure - check results carefully
testTemporalAutocorrelation(res, time = temporal_data$year)
##
## Durbin-Watson test
##
## data: simulationOutput$scaledResiduals ~ 1
## DW = 0.21232, p-value < 2.2e-16
## alternative hypothesis: true autocorrelation is not 0
Next, we diagnose the model that includes temporal dependence but
omits temperature (mod_trend3).
acf(residuals(mod_trend3), type = "correlation", plot = T)
pacf(residuals(mod_trend3), plot = T)
res <- simulateResiduals(mod_trend3)
plot(res)
testTemporalAutocorrelation(res, time = temporal_data$year)
##
## Durbin-Watson test
##
## data: simulationOutput$scaledResiduals ~ 1
## DW = 1.646, p-value = 2.107e-08
## alternative hypothesis: true autocorrelation is not 0
Finally, we diagnose the model that includes both temperature and
temporal dependence (mod_trend5).
acf(residuals(mod_trend5), type = "correlation", plot = T)
pacf(residuals(mod_trend5), plot = T)
res <- simulateResiduals(mod_trend5)
plot(res)
testTemporalAutocorrelation(res, time = temporal_data$year)
##
## Durbin-Watson test
##
## data: simulationOutput$scaledResiduals ~ 1
## DW = 0.21245, p-value < 2.2e-16
## alternative hypothesis: true autocorrelation is not 0
Interpretation principle
Do not rely on a DHARMa P value alone. Evaluate the
evidence as a whole, including:
the magnitude and direction of residual autocorrelation
the residual plots and any systematic patterns
the ecological plausibility of the proposed dependence structure
2.5 Inspect residual heterogeneity and dispersion
Residual spread can be inspected against a relevant predictor to
identify possible heteroscedasticity. testDispersion()
addresses a related but distinct question: whether the overall response
variability is greater or smaller than expected under simulations from
the fitted model.
# visual
plotResiduals(res, temporal_data$temperature)
# statistical
testDispersion(res)
##
## DHARMa nonparametric dispersion test via sd of residuals fitted vs.
## simulated
##
## data: simulationOutput
## dispersion = 0.99741, p-value = 0.952
## alternative hypothesis: two.sided
2.6 Inspect unusual observations
The simulation envelope and testOutliers() can indicate
whether the data contain more extreme observations than the fitted model
predicts. Such observations should prompt investigation of data quality,
model specification and ecological context; they should not be removed
automatically.
# visual
plot(res, quantreg = TRUE)
# statistical
testOutliers(res)
##
## DHARMa outlier test based on exact binomial test with approximate
## expectations
##
## data: res
## outliers at both margin(s) = 6, observations = 1000, p-value = 0.5952
## alternative hypothesis: true probability of success is not equal to 0.007968127
## 95 percent confidence interval:
## 0.002204982 0.013013423
## sample estimates:
## frequency of outliers (expected: 0.00796812749003984 )
## 0.006
Acknowledgement and licence
Parts of the diagnostic workflow and illustrative code were adapted from or inspired by Florian Hartig’s Advanced Regression Models with R. We modified and extended the examples using a different data-generating process and integrated simulation-based diagnostics for residual dependence, dispersion and unusual observations.
This work is licensed under a Creative Commons Attribution–NonCommercial–ShareAlike 4.0 International License (CC BY-NC-SA 4.0).
Package information
subset(data.frame(sessioninfo::package_info()), attached==TRUE, c(package, loadedversion))
## package loadedversion
## DHARMa DHARMa 0.4.7
## glmmTMB glmmTMB 1.1.3
## nlme nlme 3.1-151