| Title: | Graceful 'ggplot'-Based Graphics and Other Functions for GAMs Fitted Using 'mgcv' |
|---|---|
| Description: | Graceful 'ggplot'-based graphics and utility functions for working with generalized additive models (GAMs) fitted using the 'mgcv' package. Provides a reimplementation of the plot() method for GAMs that 'mgcv' provides, as well as 'tidyverse' compatible representations of estimated smooths. |
| Authors: | Gavin L. Simpson [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-9084-8413>), Henrik Singmann [ctb] (ORCID: <https://orcid.org/0000-0002-4842-3657>) |
| Maintainer: | Gavin L. Simpson <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.11.2-73 |
| Built: | 2026-11-14 02:12:21 UTC |
| Source: | https://github.com/gavinsimpson/gratia |
Add a confidence interval to an existing object
add_confint(object, coverage = 0.95, ...) ## S3 method for class 'smooth_estimates' add_confint(object, coverage = 0.95, ...) ## S3 method for class 'parametric_effects' add_confint(object, coverage = 0.95, ...) ## Default S3 method: add_confint(object, coverage = 0.95, ...)add_confint(object, coverage = 0.95, ...) ## S3 method for class 'smooth_estimates' add_confint(object, coverage = 0.95, ...) ## S3 method for class 'parametric_effects' add_confint(object, coverage = 0.95, ...) ## Default S3 method: add_confint(object, coverage = 0.95, ...)
object |
a R object. |
coverage |
numeric; the coverage for the interval. Must be in the range
0 < |
... |
arguments passed to other methods. |
For smooth estimates, this function computes Gaussian pointwise
intervals from the saved estimates and standard errors. It replaces any
existing limits and updates their interval metadata. To retain stored
bootstrap, shape-enforced or simultaneous limits, draw the estimates directly with
draw() without calling add_confint().
Add a constant to estimated values
add_constant(object, constant = NULL, ...) ## S3 method for class 'smooth_estimates' add_constant(object, constant = NULL, ...) ## S3 method for class 'smooth_samples' add_constant(object, constant = NULL, ...) ## S3 method for class 'mgcv_smooth' add_constant(object, constant = NULL, ...) ## S3 method for class 'parametric_effects' add_constant(object, constant = NULL, ...) ## S3 method for class 'tbl_df' add_constant(object, constant = NULL, column = NULL, ...) ## S3 method for class 'evaluated_parametric_term' add_constant(object, constant = NULL, ...)add_constant(object, constant = NULL, ...) ## S3 method for class 'smooth_estimates' add_constant(object, constant = NULL, ...) ## S3 method for class 'smooth_samples' add_constant(object, constant = NULL, ...) ## S3 method for class 'mgcv_smooth' add_constant(object, constant = NULL, ...) ## S3 method for class 'parametric_effects' add_constant(object, constant = NULL, ...) ## S3 method for class 'tbl_df' add_constant(object, constant = NULL, column = NULL, ...) ## S3 method for class 'evaluated_parametric_term' add_constant(object, constant = NULL, ...)
object |
a object to add a constant to. |
constant |
the constant to add. |
... |
additional arguments passed to methods. |
column |
character; for the |
Returns object but with the estimate shifted by the addition of
the supplied constant.
Gavin L. Simpson
Add fitted values from a model to a data frame
add_fitted(data, model, value = ".fitted", ...) ## S3 method for class 'gamm4' add_fitted(data, model, ...) ## S3 method for class 'scam' add_fitted(data, model, ...)add_fitted(data, model, value = ".fitted", ...) ## S3 method for class 'gamm4' add_fitted(data, model, ...) ## S3 method for class 'scam' add_fitted(data, model, ...)
data |
a data frame containing values for the variables used to fit the
model. Passed to |
model |
a fitted model for which a |
value |
character; the name of the variable in which model predictions will be stored. |
... |
additional arguments passed to methods. |
A data frame (tibble) formed from data and fitted values from
model, stored in ".fitted" by default.
Adds draws from the posterior distribution of model to the data object
using one of fitted_samples(), predicted_samples(), or
posterior_samples().
add_fitted_samples( data, model, ..., n_draws = NULL, seed = NULL, chains = NULL ) add_predicted_samples(data, model, ..., n_draws = NULL, seed = NULL) add_posterior_samples( data, model, ..., n_draws = NULL, seed = NULL, chains = NULL ) add_smooth_samples( data, model, ..., n_draws = NULL, seed = NULL, select = NULL, chains = NULL )add_fitted_samples( data, model, ..., n_draws = NULL, seed = NULL, chains = NULL ) add_predicted_samples(data, model, ..., n_draws = NULL, seed = NULL) add_posterior_samples( data, model, ..., n_draws = NULL, seed = NULL, chains = NULL ) add_smooth_samples( data, model, ..., n_draws = NULL, seed = NULL, select = NULL, chains = NULL )
data |
a data frame or tibble to which the posterior draws will be added. |
model |
a fitted GAM (or GAM-like) object for which a posterior draw method exists. |
... |
arguments are passed to the posterior draw function, currently one
of |
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
seed |
numeric; a value to seed the random number generator. |
chains |
positive integer or |
select |
character; select which smooth's posterior to draw from. The
default, |
load_mgcv() df <- data_sim("eg1", n = 400, seed = 42) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # add fitted samples (posterior draws of the expected value of the response) # note that there are 800 rows in the output: 400 data by `n_draws = 2` samples. df |> add_fitted_samples(m, n_draws = 2, seed = 84) # add posterior draws from smooth s(x2) df |> add_smooth_samples(m, n_draws = 2, seed = 2, select= "s(x2)")load_mgcv() df <- data_sim("eg1", n = 400, seed = 42) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # add fitted samples (posterior draws of the expected value of the response) # note that there are 800 rows in the output: 400 data by `n_draws = 2` samples. df |> add_fitted_samples(m, n_draws = 2, seed = 84) # add posterior draws from smooth s(x2) df |> add_smooth_samples(m, n_draws = 2, seed = 2, select= "s(x2)")
Add fitted values from a GAM to a data frame
## S3 method for class 'gam' add_fitted( data, model, value = ".fitted", type = "response", ..., envir = NULL, marginalise = NULL, integration = c("quadrature", "monte_carlo"), n_quad = 40L, n_integrate = 5000L, seed = NULL )## S3 method for class 'gam' add_fitted( data, model, value = ".fitted", type = "response", ..., envir = NULL, marginalise = NULL, integration = c("quadrature", "monte_carlo"), n_quad = 40L, n_integrate = 5000L, seed = NULL )
data |
a data frame containing values for the variables used to fit the
model. Passed to |
model |
a fitted model for which a |
value |
character; the name of the variable in which model predictions will be stored. |
type |
character; the type of predictions to return. See
|
... |
additional arguments passed to |
envir |
environment or |
marginalise |
|
integration |
Integration method when |
n_quad |
Initial Gauss-Hermite point count, between 2 and 1000.
Successive doubled orders, up to four times this count, and an interlaced
rule with one fewer point must agree within
|
n_integrate |
Number of Monte Carlo integration draws, at least two.
These are shared across rows and posterior coefficient draws. This count
is separate from |
seed |
Optional integer seed. An explicit seed preserves the caller's
random-number state; |
A data frame (tibble) formed from data and predictions from
model.
load_mgcv() df <- data_sim("eg1", seed = 1) df <- df[, c("y", "x0", "x1", "x2", "x3")] m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # add fitted values to our data add_fitted(df, m) # with type = "terms" or "iterms" add_fitted(df, m, type = "terms")load_mgcv() df <- data_sim("eg1", seed = 1) df <- df[, c("y", "x0", "x1", "x2", "x3")] m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # add fitted values to our data add_fitted(df, m) # with type = "terms" or "iterms" add_fitted(df, m, type = "terms")
Add partial residuals
add_partial_residuals(data, model, ...) ## S3 method for class 'gam' add_partial_residuals(data, model, select = NULL, partial_match = FALSE, ...) ## S3 method for class 'gamm4' add_partial_residuals(data, model, ...) ## S3 method for class 'scam' add_partial_residuals(data, model, ...)add_partial_residuals(data, model, ...) ## S3 method for class 'gam' add_partial_residuals(data, model, select = NULL, partial_match = FALSE, ...) ## S3 method for class 'gamm4' add_partial_residuals(data, model, ...) ## S3 method for class 'scam' add_partial_residuals(data, model, ...)
data |
a data frame containing values for the variables used to fit the
model, in fitting order. Supply either the retained fitting rows or, for
|
model |
a fitted model for which a |
... |
arguments passed to other methods. |
select |
character, logical, or numeric; which smooths to plot. If
|
partial_match |
logical; should smooths be selected by partial matches
with |
Partial residuals require working residuals and working weights from
the fitted model. Families that do not provide these, including the
location-scale families in mgcv, are not supported, even for terms in the
location predictor.
load_mgcv() df <- data_sim("eg1", seed = 1) df <- df[, c("y", "x0", "x1", "x2", "x3")] m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## add partial residuals add_partial_residuals(df, m) ## add partial residuals for selected smooths add_partial_residuals(df, m, select = "s(x0)")load_mgcv() df <- data_sim("eg1", seed = 1) df <- df[, c("y", "x0", "x1", "x2", "x3")] m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## add partial residuals add_partial_residuals(df, m) ## add partial residuals for selected smooths add_partial_residuals(df, m, select = "s(x0)")
Add residuals from a model to a data frame
add_residuals(data, model, value = ".residual", ...) ## S3 method for class 'gamm4' add_residuals(data, model, ...) ## S3 method for class 'scam' add_residuals(data, model, ...)add_residuals(data, model, value = ".residual", ...) ## S3 method for class 'gamm4' add_residuals(data, model, ...) ## S3 method for class 'scam' add_residuals(data, model, ...)
data |
a data frame containing values for the variables used to fit the
model, in fitting order. Supply either the retained fitting rows or, for
|
model |
a fitted model for which a |
value |
character; the name of the variable in which model residuals will be stored. |
... |
additional arguments passed to methods. |
A data frame (tibble) formed from data and residuals from model.
Add residuals from a GAM to a data frame
## S3 method for class 'gam' add_residuals(data, model, value = ".residual", type = "deviance", ...)## S3 method for class 'gam' add_residuals(data, model, value = ".residual", type = "deviance", ...)
data |
a data frame containing values for the variables used to fit the
model. Passed to |
model |
a fitted model for which a |
value |
character; the name of the variable in which model predictions will be stored. |
type |
character; the type of residuals to return. See
|
... |
additional arguments passed to |
A data frame (tibble) formed from data and residuals from model.
load_mgcv() df <- data_sim("eg1", seed = 1) df <- df[, c("y", "x0", "x1", "x2", "x3")] m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## add_residuals(df, m)load_mgcv() df <- data_sim("eg1", seed = 1) df <- df[, c("y", "x0", "x1", "x2", "x3")] m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## add_residuals(df, m)
Add indicators of significant change after SiZeR
add_sizer(object, type = c("change", "sizer"), ...) ## S3 method for class 'derivatives' add_sizer(object, type = c("change", "sizer"), ...) ## S3 method for class 'smooth_estimates' add_sizer(object, type = c("change", "sizer"), derivatives = NULL, ...)add_sizer(object, type = c("change", "sizer"), ...) ## S3 method for class 'derivatives' add_sizer(object, type = c("change", "sizer"), ...) ## S3 method for class 'smooth_estimates' add_sizer(object, type = c("change", "sizer"), derivatives = NULL, ...)
object |
an R object. Currently supported methods are for classes
|
type |
character; |
... |
arguments passed to other methods |
derivatives |
an object of class |
load_mgcv() df <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 42) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## first derivatives of all smooths using central finite differences d <- derivatives(m, type = "central") |> add_sizer() # default adds a .change column names(d)load_mgcv() df <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 42) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## first derivatives of all smooths using central finite differences d <- derivatives(m, type = "central") |> add_sizer() # default adds a .change column names(d)
Calculate one-dimensional accumulated local effects (ALE) of a numeric covariate, combining all model terms involving that covariate.
ale(object, ...) ## Default S3 method: ale(object, ...) ## S3 method for class 'gam' ale( object, focal, data = NULL, scale = c("link", "response", "linear_predictor"), n_bins = 40L, breaks = NULL, parameter = NULL, which_eta = NULL, center = TRUE, interval = c("confidence", "simultaneous"), ci_level = 0.95, unconditional = FALSE, frequentist = FALSE, n_sim = 10000L, n_cores = 1L, seed = NULL, block_size = 10000L, exclude = NULL, envir = NULL, ... ) ## S3 method for class 'bam' ale(object, ...) ## S3 method for class 'scam' ale(object, ..., unconditional = FALSE)ale(object, ...) ## Default S3 method: ale(object, ...) ## S3 method for class 'gam' ale( object, focal, data = NULL, scale = c("link", "response", "linear_predictor"), n_bins = 40L, breaks = NULL, parameter = NULL, which_eta = NULL, center = TRUE, interval = c("confidence", "simultaneous"), ci_level = 0.95, unconditional = FALSE, frequentist = FALSE, n_sim = 10000L, n_cores = 1L, seed = NULL, block_size = 10000L, exclude = NULL, envir = NULL, ... ) ## S3 method for class 'bam' ale(object, ...) ## S3 method for class 'scam' ale(object, ..., unconditional = FALSE)
object |
a model fitted by |
... |
named prediction controls passed to |
focal |
character; the name of one raw numeric model covariate. |
data |
optional reference data. Each row receives equal weight. By default, use the observations retained during fitting. Responses are not required. Supply raw covariates, including inputs to model expressions. |
scale |
character; |
n_bins |
positive integer; requested number of intervals. Empirical
quantiles ( |
breaks |
optional numeric interval boundaries, overriding |
parameter |
character; one distribution parameter, using the names and
aliases accepted by |
which_eta |
optional integer selecting a linear predictor instead of
|
center |
logical; subtract the empirical mean of the interpolated ALE
curve over the reference observations? If |
interval |
character; |
ci_level |
numeric; interval coverage, strictly between zero and one. |
unconditional |
logical; include smoothing parameter uncertainty if
available. Otherwise |
frequentist |
logical; use the frequentist coefficient covariance? |
n_sim, n_cores
|
positive integers; simulation count and number of cores for simultaneous intervals. Ignored for pointwise intervals. |
seed |
optional integer seed for simultaneous intervals. An explicit seed preserves the caller's random-number state around interval simulation. |
block_size |
positive integer; maximum reference rows in each prediction block. Blocks can run in parallel when workers are configured; see Details. |
exclude |
character; model terms to exclude, as in |
envir |
optional environment for functions and constants in model
expressions; see |
Within each interval, predict at its two boundaries for every reference observation in that interval, retaining its other covariates. Average the upper-minus-lower prediction differences, then accumulate these averages. Intervals are right closed, with the minimum included in the first interval. The returned curve is linearly interpolated between boundaries. Centring subtracts its mean evaluated at the reference observations, rather than an unweighted mean over boundaries. Fitting weights do not weight these averages.
On the response scale, transform endpoint predictions before differencing. Transforming a link-scale ALE curve does not produce response-scale ALE. Response-scale effects are differences in natural parameter units, not predicted parameter values, and can be negative.
Distributional families gaulss, gammals, gumbls, gevlss, shash,
twlss, and ziplss are supported. Natural units mean standard deviation
for Gaussian scale, positive scale or dispersion for logged scales, natural
Tweedie power, positive sinh-arcsinh tail parameter, and Poisson rate or
probability of presence for ziplss. Location parameters need not be response
means. Overall means combining several parameters, multinomial probabilities,
multivariate covariance parameters and grouped-family outputs are unsupported.
For other families, link-scale ALE is available for a single linear predictor;
response-scale ALE requires a supported scalar mean family.
Supported response-scale parameters are:
gaulss: location (mean) and scale (standard deviation);
gammals: location (mean) and scale (dispersion);
gumbls and gevlss: location and positive scale, plus GEV shape;
shash: location, positive scale, skewness and positive tail parameter
(named kurtosis to match gratia's parameter names);
twlss: location (mean), power and scale (dispersion);
ziplss: location (Poisson rate) and pi (probability of presence).
Raw-data recovery can require envir when a model was fitted locally and
its formula no longer retains the environment containing the fitting data.
Alternatively, supply reference data explicitly.
Coefficient gradients are averaged, accumulated and centred in the same way as the effects, retaining covariance across intervals and the centring constant. Link-scale gradients are exact; response-scale intervals use the delta method. Both interval types condition on the reference observations and boundaries. Simultaneous coverage concerns the returned boundaries, not all points between them. No uncertainty for the reference distribution is added.
Formula offsets are included and reevaluated at interval boundaries. Offsets
supplied only through the fitting function's offset argument are omitted,
following explicit-newdata prediction semantics. BAM predictions use
discrete = FALSE, including for models fitted with discrete = TRUE.
Prediction blocks use an existing pool of workers configured with
mirai::daemons(), when mirai and carrier are installed. Set block_size
small enough to give each worker a block; serial and parallel calculations
retain the same block boundaries and accumulation order. Worker startup and
model transfer can outweigh the benefit for small models or reference data.
The caller owns the pool; ale() does not start or stop workers.
n_cores controls coefficient simulation for simultaneous intervals, not the
number of prediction workers. Workers use their configured BLAS thread limits.
Data recovery and validation, centring, covariance calculations and interval simulation remain in the caller. Simultaneous bands use one shared set of coefficient deviations for all boundaries, preserving results and the caller's random-number state across worker counts. Models requiring custom prediction methods, family callbacks, contrasts or formula functions that workers cannot safely evaluate retain serial prediction. Standard arithmetic and common base and stats transformations can run on workers; local helpers, stochastic expressions, custom S3 transformation methods and other package functions retain serial prediction. Method checks do not invoke active or lazy caller bindings.
This implementation is written independently from the published ALE definition, without using code from mgcViz or ALEPlot.
A tibble of class "ale", with .focal and .parameter identifying
the curve, .value giving boundary coordinates, .ale the effects, .se
their standard errors, .crit the interval critical value, and .lower_ci
and .upper_ci the interval limits. .bin identifies the interval ending
at each boundary and .n counts its reference rows. At the initial boundary
both are zero. The ale_info attribute records computation settings without
retaining the model or reference data.
Apley, D. W. and Zhu, J. (2020). Visualizing the effects of predictor variables in black box supervised learning models. Journal of the Royal Statistical Society: Series B, 82, 1059–1086. doi:10.1111/rssb.12377.
draw.ale(), conditional_values(), response_derivatives()
load_mgcv() df <- data_sim("eg1", n = 200, seed = 42) m <- gam(y ~ s(x0) + te(x1, x2, k = c(5, 5)) + s(x3), data = df, method = "REML") a <- ale(m, focal = "x1") draw(a) # Standard deviation in its natural units, rather than reciprocal SD ml <- gam(list(y ~ s(x1), ~ x2), data = df, family = gaulss()) ale(ml, "x2", parameter = "scale", scale = "response") |> draw()load_mgcv() df <- data_sim("eg1", n = 200, seed = 42) m <- gam(y ~ s(x0) + te(x1, x2, k = c(5, 5)) + s(x3), data = df, method = "REML") a <- ale(m, focal = "x1") draw(a) # Standard deviation in its natural units, rather than reciprocal SD ml <- gam(list(y ~ s(x1), ~ x2), data = df, family = gaulss()) ale(ml, "x2", parameter = "scale", scale = "response") |> draw()
Model diagnostic plots
appraise(model, ...) ## S3 method for class 'gam' appraise( model, method = NULL, use_worm = FALSE, n_uniform = 10, n_simulate = 50, seed = NULL, type = NULL, n_bins = c("sturges", "scott", "fd"), ncol = NULL, nrow = NULL, guides = "keep", level = 0.9, ci_col = "black", ci_alpha = 0.2, point_col = "grey20", point_alpha = 1, line_col = "red", by_family = NULL, rank = NULL, scalable = NULL, scalable_threshold = 10000L, qq_bins = 1000L, density_bins = c(50L, 50L), ppcheck = FALSE, n_ppc = 50, density_method = c("kde", "histogram"), bandwidth = NULL, conditioning = NULL, ppc_batch_size = 10L, ..., n_dharma = 250L ) ## S3 method for class 'lm' appraise(model, ...) ## S3 method for class 'gamlss' appraise(model, ..., type = "quantile", seed = NULL, conditioning = NULL) ## Default S3 method: appraise( model, ..., type = NULL, seed = NULL, conditioning = NULL, n_dharma = 250L ) ## S3 method for class 'gamm4' appraise(model, conditioning = NULL, ...) ## S3 method for class 'gjrm' appraise( model, ..., type = "quantile", seed = NULL, conditioning = NULL, response = NULL, ppcheck = FALSE, by_family = NULL, n_dharma = 250L ) ## S3 method for class 'gamm' appraise(model, conditioning = NULL, ...) ## S3 method for class 'gratia_diagnostic_proxy' appraise(model, type = "quantile", ...) ## S3 method for class 'lme' appraise(model, conditioning = NULL, ...) ## S3 method for class 'merMod' appraise(model, conditioning = NULL, ...) ## S3 method for class 'sdmTMB' appraise( model, conditioning = NULL, component = "response", field_method = c("mle-mvn", "mle-eb", "mle-mvn-integrated"), ... )appraise(model, ...) ## S3 method for class 'gam' appraise( model, method = NULL, use_worm = FALSE, n_uniform = 10, n_simulate = 50, seed = NULL, type = NULL, n_bins = c("sturges", "scott", "fd"), ncol = NULL, nrow = NULL, guides = "keep", level = 0.9, ci_col = "black", ci_alpha = 0.2, point_col = "grey20", point_alpha = 1, line_col = "red", by_family = NULL, rank = NULL, scalable = NULL, scalable_threshold = 10000L, qq_bins = 1000L, density_bins = c(50L, 50L), ppcheck = FALSE, n_ppc = 50, density_method = c("kde", "histogram"), bandwidth = NULL, conditioning = NULL, ppc_batch_size = 10L, ..., n_dharma = 250L ) ## S3 method for class 'lm' appraise(model, ...) ## S3 method for class 'gamlss' appraise(model, ..., type = "quantile", seed = NULL, conditioning = NULL) ## Default S3 method: appraise( model, ..., type = NULL, seed = NULL, conditioning = NULL, n_dharma = 250L ) ## S3 method for class 'gamm4' appraise(model, conditioning = NULL, ...) ## S3 method for class 'gjrm' appraise( model, ..., type = "quantile", seed = NULL, conditioning = NULL, response = NULL, ppcheck = FALSE, by_family = NULL, n_dharma = 250L ) ## S3 method for class 'gamm' appraise(model, conditioning = NULL, ...) ## S3 method for class 'gratia_diagnostic_proxy' appraise(model, type = "quantile", ...) ## S3 method for class 'lme' appraise(model, conditioning = NULL, ...) ## S3 method for class 'merMod' appraise(model, conditioning = NULL, ...) ## S3 method for class 'sdmTMB' appraise( model, conditioning = NULL, component = "response", field_method = c("mle-mvn", "mle-eb", "mle-mvn-integrated"), ... )
model |
a fitted model supported by diagnostic_support, including lm, glm, gam/bam, gamm/gamm4, glmmTMB, univariate GJRM and sdmTMB. |
... |
arguments passed to |
method |
character or
For ordinary GAMs, |
use_worm |
logical; should a worm plot be drawn in place of the QQ plot? |
n_uniform |
numeric; number of inverse-CDF draws to average when
|
n_simulate |
numeric; number of data sets to simulate from the estimated
model when using the simulation method ( |
seed |
numeric; the random number seed to use for |
type |
character or |
n_bins |
character or numeric; either the number of bins or a string indicating how to calculate the number of bins. |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots. |
guides |
character; one of |
level |
numeric; the coverage level for QQ plot reference intervals.
Must be strictly |
ci_alpha, ci_col
|
Deprecated; use |
point_col, point_alpha
|
Deprecated; use |
line_col |
Deprecated; use |
by_family |
logical or |
rank |
logical or |
scalable |
Logical or |
scalable_threshold |
Positive integer; automatic switching threshold. |
qq_bins |
Maximum number of QQ/worm points per family component, including endpoints. |
density_bins |
Positive integer or pair giving heatmap grid dimensions. |
ppcheck |
logical; replace the residual histogram with a
|
n_ppc |
positive integer; number of posterior predictive data sets
when |
density_method |
Conditional-density estimator: |
bandwidth |
Optional pair of positive bandwidths for the predictor and
residual axes, in their plotted units. |
conditioning |
character or |
ppc_batch_size |
positive integer; number of posterior predictive draws to process together for scalable plots. Changing the batch size does not change results for a fixed seed. |
n_dharma |
positive integer; number of response simulations for
|
response |
|
component |
character; for delta sdmTMB models, select the complete
|
field_method |
how to treat fitted sdmTMB fields: hold one posterior
draw fixed ( |
Use type = "dharma" for simulation-based PIT residuals calculated
internally using gratia's response generators; no DHARMa or mgcViz
dependency is needed. These residuals lie in [0, 1], including exact
endpoints, and do not require a response CDF. n_dharma controls their
simulation count. All residual panels share one calculated vector.
QQ and worm plots require method = NULL and use uniform reference
quantiles, with approximate pointwise bands for independent responses.
Bands are omitted for dependent responses. Censored and multivariate
outcomes are unsupported. See dharma_residuals() for the calculation.
Use type = "surrogate" for mgcv::ocat() and mgcv::multinom() GAMs.
The former uses a scalar latent logistic residual; the latter retains
all category utilities, including category 0, as separate panels with
centred Gumbel references. QQ and worm plots require method = NULL.
Each appraisal shares one residual draw across panels, with the same
draw in ordinary and scalable displays. Multinomial residuals are plotted
against their own category probabilities; observed-versus-fitted panels
compare category indicators with those probabilities. Pointwise bands
are calculated separately for each utility. See surrogate_residuals().
With type = NULL, ordinary lm/glm/GAM fits use deviance residuals.
Models fitted with mgcv::gfam() use randomised quantile (Dunn–Smyth)
residuals when every active component supplies a supported CDF and
probability limits for discrete or censored observations. Otherwise, a
message identifies unsupported components and all
components use deviance residuals; requesting type = "quantile" explicitly
is an error when any component is unsupported. Components never mix
residual scales. Invalid encodings or numerical CDF failures are errors.
Quantile residuals use each component's fitted parameters, dispersion and
weights, including binomial trial counts and Gaussian precision weights.
Gamma (including precision weights), negative binomial, beta, scaled-t,
Tweedie, inverse Gaussian, ordinal and zero-inflated Poisson components are
supported. Unrecognised custom-family bounds remain unsupported.
A custom CDF must also support the probabilities just below discrete
values and at censoring limits. Replacements for recognised family CDFs
must use the same arguments and probability conventions. Scalar uncensored
cnorm(), clog() and
cpois() components are supported; genuine censoring requires recoverable,
aligned censoring bounds. Matrix censored responses rejected by gfam()
and upstream fitting failures are not repaired.
Use response = NULL to check every grouped-family component or a single
integer to select a component by its position in the mgcv::gfam() family
list. Repeated families remain distinct. Selection filters fitting
observations without refitting the model and retains original component
labels. by_family independently controls the layout of the selected data.
With an explicit seed, selected residuals match the corresponding rows of
an all-component calculation whenever all components support that calculation.
by_family = NULL pools quantile residuals with colours identifying indexed
family components, including repeated uses of the same family. Traditional
residuals use component facets with free axes by default. The pooled
residual-versus-predictor plot uses within-component predictor ranks:
(rank(eta, ties.method = "average") - 0.5) / n, where n counts the finite
observations included for that component; constants map to 0.5.
Facets retain original linear predictors. Use rank to override this choice
independently of residual type or layout. The links and original predictor
values can have different meanings across components; ranks compare
positions within components, not effects on a common response scale.
Pooled histograms use common bin edges and component-specific densities.
Quantile QQ and worm plots compare to fixed standard-normal quantiles,
with an identity line or zero line. Independent responses have exact
pointwise reference bands for ordered residuals. For dependent responses,
bands use simulations that preserve dependence when a joint generator is
available; otherwise they are omitted with an explanation. Bands condition
on fitted parameters, exclude estimation uncertainty and do not provide
simultaneous coverage. References calculated from simulation ranks also
use simulated bands; see diagnostic_support. Worm plots
subtract the same theoretical quantiles from residuals and reference bands.
appraise() computes one seeded residual vector shared by its residual
panels and always separates observed-versus-fitted values by component,
because response units differ. Standalone observed_fitted_plot() allows
explicit pooling. Ordinal panels use expected category codes.
Scalable plots aggregate all observations before rendering. Residual heatmaps show conditional density; observed-versus-fitted heatmaps show counts. Point styling applies to QQ/worm points, and heatmap fill scales can be changed with ggplot scales. QQ references average draws as they are generated or compute exact pooled quantiles using temporary files above the configured memory threshold; see diagnostic_support. Supported univariate GJRM::gamlss models use quantile residuals by default.
If the response expectation does not exist, the observed-versus-fitted panel explains why it is unavailable. Other supported panels remain usable. Prepared diagnostic objects can be given a new conditioning or field choice; the model is prepared again so all panels use the requested choice.
The wording used in mgcv::qq.gam() uses direct in reference to the
simulated residuals method (method = "simulated"). To avoid confusion,
method = "direct" is deprecated in favour of method = "uniform".
The plots are produced by functions qq_plot(),
residuals_linpred_plot(), residuals_hist_plot(),
observed_fitted_plot(), and optionally
posterior_predictive_plot().
load_mgcv() # Simulate an additive Gaussian response and fit a GAM dat <- data_sim("eg1", n = 200, scale = 2, seed = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # Inspect residuals, fitted values and the residual distribution appraise(mod, seed = 42)load_mgcv() # Simulate an additive Gaussian response and fit a GAM dat <- data_sim("eg1", n = 200, scale = 2, seed = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # Inspect residuals, fitted values and the residual distribution appraise(mod, seed = 42)
Coefficient matrices retain their chain mapping in an attribute. Sampled
quantities use their .chain, .iteration, and .draw columns. A plain
matrix without a mapping is treated as one chain; chain boundaries are never
inferred from its number of rows. Filtering must leave the same consecutive
iterations in every chain. Missing observations remain missing variables.
as_mcmc_draws( x, format = c("draws_array", "draws_df", "mcmc.list", "array"), value = NULL )as_mcmc_draws( x, format = c("draws_array", "draws_df", "mcmc.list", "array"), value = NULL )
x |
A coefficient matrix from |
format |
One of |
value |
Column containing sampled values. By default the appropriate
column is selected from |
An iteration by chain by variable array, a posterior draws object, or a coda list of chains. Variable names identify sampled quantities and their observation rows, parameters, or smooths.
ggplot2 and assembles them as a listGeneric function for assembling plot objects created from R objects, using
the ggplot2 package.
assemble(object, ..., label_control = NULL) ## S3 method for class 'gamm4' assemble(object, ...)assemble(object, ..., label_control = NULL) ## S3 method for class 'gamm4' assemble(object, ...)
object |
and R object to plot. |
... |
arguments passed to other methods. |
label_control |
Optional layout settings created by
|
A list of ggplot2::ggplot() objects.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Gavin L. Simpson
Plots smooth and parametric contributions from a fitted GAM model using
ggplot2::ggplot().
For models fitted by mgcv::gamm(), assemble() and draw() use the
fitted gam component.
## S3 method for class 'gam' assemble( object, data = NULL, select = NULL, parametric = NULL, terms = NULL, residuals = FALSE, scales = c("free", "fixed"), ci_level = 0.95, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, unconditional = FALSE, overall_uncertainty = TRUE, constant = NULL, fun = NULL, dist = 0.1, rug = TRUE, distinct_rug = TRUE, contour = TRUE, grouped_by = deprecated(), ci_alpha = 0.2, ci_col = "black", smooth_col = "black", resid_col = "steelblue3", contour_col = "black", n_contour = NULL, partial_match = FALSE, discrete_colour = NULL, discrete_fill = NULL, continuous_colour = NULL, continuous_fill = NULL, position = "identity", angle = NULL, ncol = NULL, nrow = NULL, guides = "keep", widths = NULL, heights = NULL, crs = NULL, default_crs = NULL, lims_method = "geometry_bbox", wrap = TRUE, caption = TRUE, envir = NULL, surface = c("raster", "tile", "3d"), surface_3d = list(), ci_3d = FALSE, ci_3d_alpha = 0.15, ci_3d_col = "grey60", back_transform = FALSE, re_levels = NULL, mrf_plot = c("effects", "qq"), interval = c("confidence", "simultaneous"), n_sim = 10000, n_cores = 1, seed = NULL, interval_method = c("auto", "gaussian", "bootstrap", "shape"), frequentist = FALSE, shape_source = c("gaussian", "bootstrap"), ..., variables = NULL, simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list(), cyclic = c("cartesian", "polar"), polar_args = list(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz"), time_varying_style = c("ribbon", "pointrange") ) ## S3 method for class 'gamm' assemble(object, ...) ## S3 method for class 'scam' assemble(object, ..., overall_uncertainty = FALSE, centre = c("model", "plot"))## S3 method for class 'gam' assemble( object, data = NULL, select = NULL, parametric = NULL, terms = NULL, residuals = FALSE, scales = c("free", "fixed"), ci_level = 0.95, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, unconditional = FALSE, overall_uncertainty = TRUE, constant = NULL, fun = NULL, dist = 0.1, rug = TRUE, distinct_rug = TRUE, contour = TRUE, grouped_by = deprecated(), ci_alpha = 0.2, ci_col = "black", smooth_col = "black", resid_col = "steelblue3", contour_col = "black", n_contour = NULL, partial_match = FALSE, discrete_colour = NULL, discrete_fill = NULL, continuous_colour = NULL, continuous_fill = NULL, position = "identity", angle = NULL, ncol = NULL, nrow = NULL, guides = "keep", widths = NULL, heights = NULL, crs = NULL, default_crs = NULL, lims_method = "geometry_bbox", wrap = TRUE, caption = TRUE, envir = NULL, surface = c("raster", "tile", "3d"), surface_3d = list(), ci_3d = FALSE, ci_3d_alpha = 0.15, ci_3d_col = "grey60", back_transform = FALSE, re_levels = NULL, mrf_plot = c("effects", "qq"), interval = c("confidence", "simultaneous"), n_sim = 10000, n_cores = 1, seed = NULL, interval_method = c("auto", "gaussian", "bootstrap", "shape"), frequentist = FALSE, shape_source = c("gaussian", "bootstrap"), ..., variables = NULL, simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list(), cyclic = c("cartesian", "polar"), polar_args = list(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz"), time_varying_style = c("ribbon", "pointrange") ) ## S3 method for class 'gamm' assemble(object, ...) ## S3 method for class 'scam' assemble(object, ..., overall_uncertainty = FALSE, centre = c("model", "plot"))
object |
a fitted GAM, the result of a call to |
data |
an optional data frame that is used to supply the data at which the smooths will be evaluated and plotted. This is usually not needed, but is an option if you need fine control over exactly what data are used for plotting. |
select |
character, logical, or numeric; which smooths to plot. If
|
parametric |
logical or |
terms |
character; which model parametric terms should be drawn? The
Default of |
residuals |
logical; should partial residuals for a smooth be drawn? Ignored for anything but a simple univariate smooth. If the model does not provide working residuals and working weights, warns once and draws the smooths without partial residuals. |
scales |
character; should all univariate smooths be plotted with the
same y-axis scale? If Currently does not affect the y-axis scale of plots of the parametric terms. |
ci_level |
numeric between 0 and 1; the coverage of credible interval. |
n |
numeric; the number of points over the range of the covariate at which to evaluate a univariate smooth. |
n_2d |
numeric; the number of points along each of the first two axes
of a smooth surface, including surface panels of higher-dimensional smooths.
The default is 50 in plotting and plot-preparation functions. If |
n_3d |
numeric; the number of new observations to generate for the third
dimension of a 3D smooth. Factor conditioning dimensions retain at most
this many levels, taking the first levels in fitted order. Explicit
|
n_4d |
numeric; the number of new observations to generate for the
dimensions higher than 2 (!) of a kD smooth (k >= 4). For example, if
the smooth is a 4D smooth, each of dimensions 3 and 4 will get |
unconditional |
logical; should confidence intervals include the
uncertainty due to smoothness selection? If |
overall_uncertainty |
logical; should the uncertainty in the model
constant term be included in the standard errors of smooth and parametric
effects? For parametric effects this includes the intercept variance and
its covariance with the term, without changing the partial estimates.
Each term uses the intercept of its own linear predictor.
Native scasm models are routed to |
constant |
numeric; a constant to add to the estimated values of the
smooth. |
fun |
function; a function that will be applied to the estimated values
and confidence interval before plotting. Can be a function or the name of a
function. For simultaneous bands it must be monotone over the entire band;
endpoint transformation alone does not preserve non-monotone band coverage.
Function |
dist |
numeric; if greater than 0, this is used to determine when
a location is too far from data to be plotted when plotting 2-D smooths.
The data are scaled into the unit square before deciding what to exclude,
and |
rug |
logical; draw a rug plot at the bottom of each plot for 1-D smooths or plot locations of data for higher dimensions. |
distinct_rug |
logical; should the data for the rug plots be reduced to the distinct values? |
contour |
logical; should contours be draw on the plot using
|
grouped_by |
Deprecated; use |
ci_alpha |
Deprecated; use |
ci_col |
Deprecated; use |
smooth_col |
Deprecated; use |
resid_col |
Deprecated; use |
contour_col |
Deprecated; use |
n_contour |
numeric; the number of contour bins. Will result in
|
partial_match |
logical; should smooths be selected by partial matches
with |
discrete_colour |
a suitable colour scale to be used when plotting discrete variables. |
discrete_fill |
a suitable fill scale to be used when plotting discrete variables. |
continuous_colour |
a suitable colour scale to be used when plotting continuous variables. |
continuous_fill |
a suitable fill scale to be used when plotting continuous variables. |
position |
Position adjustment, either as a string, or the result of a call to a position adjustment function. |
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
guides |
character; one of |
widths, heights
|
The relative widths and heights of each column and
row in the grid. Will get repeated to match the dimensions of the grid. If
there is more than 1 plot and |
crs |
the coordinate reference system (CRS) to use for the plot. All
data will be projected into this CRS. See |
default_crs |
the coordinate reference system (CRS) to use for non-sf
layers added to spherical plots. The default, |
lims_method |
character; affects how spherical plot axis limits are
determined. The default, |
wrap |
logical; wrap plots as a patchwork? If |
caption |
logical; show the smooth type in the caption of each plot? |
envir |
an optional environment for looking up data, functions and constants. Defaults to the model's evaluation environment. |
surface |
character; one of |
surface_3d |
named list of view options passed to |
ci_3d |
logical; add lower and upper interval surfaces to numeric
smooth and parametric effect panels when |
ci_3d_alpha |
Deprecated; use |
ci_3d_col |
Deprecated; use |
back_transform |
logical; plot covariates on their original scale?
Defaults to |
re_levels |
named list of factor level labels to retain in tensor products
with random-effect margins, for example |
mrf_plot |
character; display Markov random field smooths as area-labelled
estimates and intervals ( |
interval |
character; |
n_sim, n_cores
|
positive integers; coefficient draws and simulation cores for simultaneous bands. Parallel simulation requires OpenMP support. |
seed |
integer or |
interval_method |
character; "auto" uses stored scasm bootstrap draws
for pointwise intervals when available, and Gaussian intervals otherwise.
Use "gaussian" to request covariance-based limits or "bootstrap" to
require stored draws. Simultaneous bootstrap bands are not supported.
|
frequentist |
logical; use frequentist covariance for smooth-component intervals? The default uses approximate Bayesian covariance. Parametric effect intervals retain their existing Bayesian covariance calculation. |
shape_source |
character; initial uncertainty for |
... |
Additional smooth plotting arguments, including |
variables |
Character vector giving every covariate of the selected
smooths exactly once, in plotting order: x, y, then the conditioning
covariate for 3D smooths, or facet rows and columns for 4D smooths.
When supplied, selected smooths must use the same covariates. Use fitted coordinate names,
such as |
simultaneous_method |
character; calibration for simultaneous bands.
The default, |
simultaneous_domain |
numeric pair of increasing finite endpoints, or
a named list of such pairs keyed by spline coordinate. For tube bands,
|
tube_control |
named list controlling numerical tube calibration:
|
cyclic |
character; use Cartesian coordinates ( |
polar_args |
named list of options passed to |
grouped |
character or |
show_ci |
character or |
time_varying_style |
Display sdmTMB time-varying coefficients using
a line, points and interval ribbon ( |
centre |
character; for SCAM models, |
Smooth and parametric plot subtitles identify the model part or
distributional parameter as described in draw.gam(). Custom labels, including
subtitle, can be passed through .... Use cyclic = "polar" to draw
one-dimensional cyclic smooths with polar coordinates; polar_args
customizes the coordinate display as described in draw.gam().
A list of ggplot2::ggplot() objects.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Internally, plots of each smooth are created using ggplot2::ggplot()
and composed into a single plot using patchwork::wrap_plots(). As a
result, it is not possible to use + to add to the plots in the way one
might typically work with ggplot() plots. Instead, use the & operator;
see the examples.
Gavin L. Simpson
load_mgcv() # simulate some data df1 <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 2) # fit GAM m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df1, method = "REML") # assemble plots of all smooths assemble(m1) # can be passed to patchwork::wrap_plots() suppressPackageStartupMessages(library("patchwork")) assemble(m1) |> wrap_plots(ncol = 2, nrow = 2) # Prepare individual plots from a GAMM m2 <- gamm(y ~ s(x0) + x1, data = df1, method = "REML") gamm_plots <- assemble(m2) gamm_plots[[1]]load_mgcv() # simulate some data df1 <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 2) # fit GAM m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df1, method = "REML") # assemble plots of all smooths assemble(m1) # can be passed to patchwork::wrap_plots() suppressPackageStartupMessages(library("patchwork")) assemble(m1) |> wrap_plots(ncol = 2, nrow = 2) # Prepare individual plots from a GAMM m2 <- gamm(y ~ s(x0) + x1, data = df1, method = "REML") gamm_plots <- assemble(m2) gamm_plots[[1]]
Basis expansions from a definition of a smoother using the syntax of mgcv's
smooths via mgcv::s()., mgcv::te(), mgcv::ti(), and mgcv::t2(), or
directly from a fitted GAM(M).
basis(object, ...) ## S3 method for class 'gam' basis( object, select = NULL, term = deprecated(), data = NULL, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, partial_match = FALSE, envir = NULL, ..., variables = NULL, unweighted = FALSE ) ## S3 method for class 'scam' basis( object, select = NULL, term = deprecated(), data = NULL, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, partial_match = FALSE, ..., variables = NULL, unweighted = FALSE ) ## S3 method for class 'gamm' basis( object, select = NULL, term = deprecated(), data = NULL, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, partial_match = FALSE, ..., variables = NULL, unweighted = FALSE ) ## S3 method for class 'gamm4' basis( object, select = NULL, term = deprecated(), data = NULL, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, partial_match = FALSE, ..., variables = NULL, unweighted = FALSE ) ## Default S3 method: basis( object, data, knots = NULL, constraints = FALSE, at = NULL, diagonalize = FALSE, coefficients = NULL, envir = NULL, ..., variables = NULL )basis(object, ...) ## S3 method for class 'gam' basis( object, select = NULL, term = deprecated(), data = NULL, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, partial_match = FALSE, envir = NULL, ..., variables = NULL, unweighted = FALSE ) ## S3 method for class 'scam' basis( object, select = NULL, term = deprecated(), data = NULL, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, partial_match = FALSE, ..., variables = NULL, unweighted = FALSE ) ## S3 method for class 'gamm' basis( object, select = NULL, term = deprecated(), data = NULL, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, partial_match = FALSE, ..., variables = NULL, unweighted = FALSE ) ## S3 method for class 'gamm4' basis( object, select = NULL, term = deprecated(), data = NULL, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, partial_match = FALSE, ..., variables = NULL, unweighted = FALSE ) ## Default S3 method: basis( object, data, knots = NULL, constraints = FALSE, at = NULL, diagonalize = FALSE, coefficients = NULL, envir = NULL, ..., variables = NULL )
object |
a smooth specification, the result of a call to one of
|
... |
other arguments passed to |
select |
character; select smooths in a fitted model |
term |
|
data |
a data frame containing the variables used in |
n |
numeric; the number of points over the range of the covariate at which to evaluate a univariate smooth. |
n_2d |
numeric; the number of points along each of the first two axes
of a smooth surface, including surface panels of higher-dimensional smooths.
The default is 50 in plotting and plot-preparation functions. If |
n_3d |
numeric; the number of new observations to generate for the third dimension of a 3D smooth. |
n_4d |
numeric; the number of new observations to generate for the
dimensions higher than 2 (!) of a kD smooth (k >= 4). For example, if
the smooth is a 4D smooth, each of dimensions 3 and 4 will get |
partial_match |
logical; in the case of character |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
variables |
character; smooth covariates in plotting order. Supply every
covariate exactly once. The first two define surface axes and the remaining
covariates define conditioning facets. Selected smooths must have the same
covariates. If |
unweighted |
logical; for fitted models, return basis functions without
multiplying by fitted coefficients? The default, |
knots |
a list or data frame with named components containing
knots locations. Names must match the covariates for which the basis
is required. See |
constraints |
logical; should identifiability constraints be applied to
the smooth basis. See argument |
at |
a data frame containing values of the smooth covariate(s) at which the basis should be evaluated. |
diagonalize |
logical; if |
coefficients |
numeric; vector of values for the coefficients of the basis functions. |
When evaluating a fitted smooth at explicit data, missing covariates required
by that smooth produce NA basis values. Missing values in other model
variables do not discard otherwise evaluable rows.
The covariate order chosen by variables also determines which automatically
generated axes use n_2d, n_3d, and n_4d. Supplied data or at values
are unchanged. Set a resolution argument to NULL to use n instead.
A tibble with class basis. Its plot_variables attribute stores
covariate orders by smooth label for subsequent plotting. When the basis
is shared across factor levels, factor_by_groups records the smooth
labels that draw() combines. The returned rows retain each level.
Gavin L. Simpson
load_mgcv() df <- data_sim("eg4", n = 400, seed = 42) bf <- basis(s(x0), data = df) bf <- basis(s(x2, by = fac, bs = "bs"), data = df, constraints = TRUE)load_mgcv() df <- data_sim("eg4", n = 400, seed = 42) bf <- basis(s(x0), data = df) bf <- basis(s(x2, by = fac, bs = "bs"), data = df, constraints = TRUE)
Extract basis dimension of a smooth
basis_size(object, ...) ## S3 method for class 'mgcv.smooth' basis_size(object, ...) ## S3 method for class 'gam' basis_size(object, ...) ## S3 method for class 'gamm' basis_size(object, ...) ## S3 method for class 'gamm4' basis_size(object, ...) ## S3 method for class 'scam' basis_size(object, ...)basis_size(object, ...) ## S3 method for class 'mgcv.smooth' basis_size(object, ...) ## S3 method for class 'gam' basis_size(object, ...) ## S3 method for class 'gamm' basis_size(object, ...) ## S3 method for class 'gamm4' basis_size(object, ...) ## S3 method for class 'scam' basis_size(object, ...)
object |
A fitted GAM(M). Currently |
... |
Arguments passed to other methods. |
load_mgcv() df <- data_sim("eg1", n = 200, seed = 1) m <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df) basis_size(m)load_mgcv() df <- data_sim("eg1", n = 200, seed = 1) m <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df) basis_size(m)
Data generated from a hypothetical study of bird movement along a migration
corridor, sampled throughout the year. This dataset consists of simulated
sample records of numbers of observed locations of 100 tagged individuals
each from six species of bird, at ten locations along a latitudinal gradient,
with one observation taken every four weeks. Counts were simulated randomly
for each species in each location and week by creating a species-specific
migration curve that gave the probability of finding an individual of a
given species in a given location, then simulated the distribution of
individuals across sites using a multinomial distribution, and subsampling
that using a binomial distribution to simulation observation error (i.e.
not every bird present at a location would be detected). The data set
(bird_move) consists of the variables count, latitude, week and
species.
A data frame
Pedersen EJ, Miller DL, Simpson GL, Ross N. 2018. Hierarchical generalized additive models: an introduction with mgcv. PeerJ Preprints 6:e27320v1 doi:10.7287/peerj.preprints.27320v1.
## S3 method for class 'gamm4' boundary(x, ...) boundary(x, ...) ## S3 method for class 'soap.film' boundary(x, ...) ## S3 method for class 'gam' boundary(x, select, ...)## S3 method for class 'gamm4' boundary(x, ...) boundary(x, ...) ## S3 method for class 'soap.film' boundary(x, ...) ## S3 method for class 'gam' boundary(x, select, ...)
x |
an R object. Currently only objects that inherit from classes
|
... |
arguments passed to other methods. |
select |
character; the label of the soap film smooth from which to extract the boundary. |
A list of lists or data frames specifying the loops that define the boundary of the soap film smooth.
Given a vector indexing the smooths of a GAM, returns a logical vector selecting the requested smooths.
check_user_select_smooths( smooths, select = NULL, partial_match = FALSE, model_name = NULL )check_user_select_smooths( smooths, select = NULL, partial_match = FALSE, model_name = NULL )
smooths |
character; a vector of smooth labels. |
select |
numeric, logical, or character vector of selected smooths. |
partial_match |
logical; in the case of character |
model_name |
character; a model name that will be used in error messages. |
A logical vector the same length as length(smooths) indicating
which smooths have been selected.
Gavin L. Simpson
scam model.Extract coefficients from a fitted scam model.
## S3 method for class 'scam' coef(object, parametrized = TRUE, ...)## S3 method for class 'scam' coef(object, parametrized = TRUE, ...)
object |
a model object fitted by |
parametrized |
logical; extract parametrized coefficients, which respect the linear inequality constraints of the model. |
... |
other arguments. |
Compare smooths across models
compare_smooths( model, ..., select = NULL, smooths = deprecated(), n = 100, n_2d = 50, data = NULL, unconditional = FALSE, overall_uncertainty = TRUE, partial_match = FALSE, envir = NULL, dist = NULL )compare_smooths( model, ..., select = NULL, smooths = deprecated(), n = 100, n_2d = 50, data = NULL, unconditional = FALSE, overall_uncertainty = TRUE, partial_match = FALSE, envir = NULL, dist = NULL )
model |
Primary model for comparison. |
... |
Additional models to compare smooths against those of |
select |
character; select which smooths to compare. The default
( |
smooths |
|
n |
numeric; the number of points over the range of the covariate at which to evaluate a univariate smooth. |
n_2d |
numeric; the number of points along each of the first two axes
of a smooth surface, including surface panels of higher-dimensional smooths.
The default is 50 in plotting and plot-preparation functions. If |
data |
a data frame of covariate values at which to evaluate the smooth. |
unconditional |
logical; if |
overall_uncertainty |
logical; should the uncertainty in the model constant term be included in the standard error of the evaluate values of the smooth? |
partial_match |
logical; should smooths be selected by partial matches
with |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
dist |
numeric; if greater than 0, this is used to determine when
a location is too far from data to be plotted when plotting 2-D smooths.
The data are scaled into the unit square before deciding what to exclude,
and |
Two-variable smooths are evaluated at common locations. Automatic grids span
the intersection of the models' observed covariate ranges; factor levels must
overlap. Supplied data are evaluated as given, without filling gaps.
Each selected smooth label must occur exactly once in every model and use
the same covariates, including any by variable. Numeric and logical select
refer to the primary model; matching labels are then used in every model.
Estimates are contributions of individual smooths to the linear predictor, on its link scale, with the centring constraints used in each fitted model. They exclude the intercept and other model terms. Different fitting data can change the centring, so a surface difference can include a constant shift. It is the difference between these fitted smooth contributions, rather than a difference between fitted responses.
The result retains one row per model and smooth, with estimates in the data
list column. For distributional models, .parameter retains the label for
the linear predictor, while .model identifies the input model. Use
draw.compare_smooths() for faceted surface comparisons or
estimated surface differences. Smooths with more than two covariates can be
evaluated but cannot be drawn by this method.
load_mgcv() dat <- data_sim("eg1", seed = 2) ## models to compare smooths across - artificially create differences m1 <- gam(y ~ s(x0, k = 5) + s(x1, k = 5) + s(x2, k = 5) + s(x3, k = 5), data = dat, method = "REML" ) m2 <- gam(y ~ s(x0, bs = "ts") + s(x1, bs = "ts") + s(x2, bs = "ts") + s(x3, bs = "ts"), data = dat, method = "REML") ## build comparisons comp <- compare_smooths(m1, m2) comp ## notice that the result is a nested tibble draw(comp) # Simulate a noisy response over two continuous covariates, x and z surf <- data_sim("eg2", n = 100, seed = 7) # Fit two small bases to the same surface data coarse <- gam(y ~ s(x, z, k = 10), data = surf, method = "REML") fine <- gam(y ~ s(x, z, k = 15), data = surf, method = "REML") # Compare surfaces on shared axes and a shared colour scale surfaces <- compare_smooths(coarse, fine, n_2d = 20) draw(surfaces) # Show coarse minus fine, with a colour scale centred on zero draw(surfaces, show = "difference", pair = c("coarse", "fine"))load_mgcv() dat <- data_sim("eg1", seed = 2) ## models to compare smooths across - artificially create differences m1 <- gam(y ~ s(x0, k = 5) + s(x1, k = 5) + s(x2, k = 5) + s(x3, k = 5), data = dat, method = "REML" ) m2 <- gam(y ~ s(x0, bs = "ts") + s(x1, bs = "ts") + s(x2, bs = "ts") + s(x3, bs = "ts"), data = dat, method = "REML") ## build comparisons comp <- compare_smooths(m1, m2) comp ## notice that the result is a nested tibble draw(comp) # Simulate a noisy response over two continuous covariates, x and z surf <- data_sim("eg2", n = 100, seed = 7) # Fit two small bases to the same surface data coarse <- gam(y ~ s(x, z, k = 10), data = surf, method = "REML") fine <- gam(y ~ s(x, z, k = 15), data = surf, method = "REML") # Compare surfaces on shared axes and a shared colour scale surfaces <- compare_smooths(coarse, fine, n_2d = 20) draw(surfaces) # Show coarse minus fine, with a colour scale centred on zero draw(surfaces, show = "difference", pair = c("coarse", "fine"))
Compare full fitted values between pairs of factor levels, conditional on
covariate values. Parametric effects and smooths are included unless excluded
explicitly. Unlike difference_smooths(), these are differences of predictions,
rather than differences of selected smooth functions.
conditional_differences( model, by, condition = NULL, data = NULL, scale = c("response", "link", "linear_predictor"), ... ) ## S3 method for class 'gam' conditional_differences( model, by, condition = NULL, data = NULL, scale = c("response", "link", "linear_predictor"), n_vals = NULL, ci_level = 0.95, complete = TRUE, unconditional = FALSE, uncertainty = c("delta", "simulation"), n_sim = 10000, seed = NULL, n_cores = 1, method = c("gaussian", "mh", "inla", "user"), draws = NULL, mvn_method = c("mvnfast", "mgcv"), burnin = 1000, thin = 1, t_df = 40, rw_scale = 0.25, envir = NULL, ..., interval = c("confidence", "simultaneous"), simultaneous_scope = c("contrast", "all") ) ## S3 method for class 'gamm4' conditional_differences(model, ...) ## S3 method for class 'scam' conditional_differences(model, ..., unconditional = FALSE)conditional_differences( model, by, condition = NULL, data = NULL, scale = c("response", "link", "linear_predictor"), ... ) ## S3 method for class 'gam' conditional_differences( model, by, condition = NULL, data = NULL, scale = c("response", "link", "linear_predictor"), n_vals = NULL, ci_level = 0.95, complete = TRUE, unconditional = FALSE, uncertainty = c("delta", "simulation"), n_sim = 10000, seed = NULL, n_cores = 1, method = c("gaussian", "mh", "inla", "user"), draws = NULL, mvn_method = c("mvnfast", "mgcv"), burnin = 1000, thin = 1, t_df = 40, rw_scale = 0.25, envir = NULL, ..., interval = c("confidence", "simultaneous"), simultaneous_scope = c("contrast", "all") ) ## S3 method for class 'gamm4' conditional_differences(model, ...) ## S3 method for class 'scam' conditional_differences(model, ..., unconditional = FALSE)
model |
a fitted GAM object. |
by |
character vector naming factors that define comparison groups.
For multiple factors, groups are joint combinations of their levels and
all pairs of groups are compared. To compare one factor within levels of
another, put the latter in |
condition |
character vector or list specifying evaluation covariates,
as in |
data |
optional data frame used to generate condition values and
determine covariate classes. Explicit values in |
scale |
character; which scale should predictions be returned on? |
... |
arguments passed to prediction, such as |
n_vals |
positive integer or |
ci_level |
numeric; a number on interval (0,1) giving the coverage for credible intervals. |
complete |
logical; include all combinations of comparison and
conditioning factors? With |
unconditional |
logical; include smoothing-parameter uncertainty in the Bayesian covariance, if available, for delta intervals and Gaussian draws. This argument does not modify MH or user-supplied draws. |
uncertainty |
character; |
n_sim |
integer; number of draws for posterior simulation or calibration
of delta-method simultaneous intervals. Ignored for pointwise delta intervals
and for simulation with |
seed |
integer or |
n_cores |
integer; number of cores used by |
method |
character; posterior sampler used by |
draws |
matrix of posterior coefficient draws, one draw per row in model
coefficient order, used with |
mvn_method |
character; one of |
burnin |
numeric; the length of any initial burn in period to discard.
See |
thin |
positive integer; retain every |
t_df |
numeric; degrees of freedom for static multivariate t proposal.
See |
rw_scale |
numeric; factor by which to scale posterior covariance
matrix when generating random walk proposals. See |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
interval |
character; |
simultaneous_scope |
character; |
Differences are group 1 minus group 2, with groups ordered by model factor levels. Both groups use the same values of all other covariates. On the response scale the inverse link is applied to each prediction before subtraction. Shared terms can therefore affect response-scale differences even when they cancel on the link scale.
Intervals describe uncertainty in conditional mean differences, not observation
noise. Simulation uses fitted_samples() once for the entire prediction
grid, retaining dependence between predictions by subtracting within draws.
The estimate is always the difference of fitted predictions. Pointwise
simulation intervals need not be centred on this estimate.
Simultaneous intervals use the ci_level quantile of the maximum absolute
standardized deviation over the selected coverage set. They are symmetric
about .diff, with half-width .crit * .se. For uncertainty = "delta",
one shared batch of zero-mean Gaussian coefficient deviations is generated
from the Bayesian covariance matrix. Response-scale
differences use a first-order Taylor approximation. The covariance must be
positive semidefinite; singular covariance matrices are supported.
Sampler arguments method, draws, mvn_method, burnin,
thin, t_df, and rw_scale apply only to uncertainty = "simulation".
For uncertainty = "simulation", deviations are posterior difference draws
minus .diff, standardized by their sample standard deviations. Draws are
transformed to the response scale before differencing; invalid inverse-link
domains or response means cause an error rather than discarded draws.
Zero-variance draws that disagree with .diff cannot calibrate a band and
cause an error. Deterministic rows agreeing with .diff have zero width.
Simultaneous coverage is approximate posterior coverage on the finite
evaluation grid, not between its points or outside its range, nor exact
frequentist coverage. Increase n_vals to evaluate a denser grid. Bands are
not clipped to the response-difference range (e.g. [-1, 1] for probabilities).
They need not contain the equal-tailed pointwise simulation intervals.
exclude sets the named term contributions to zero. In particular, excluding
random effects does not integrate over their distribution. Offsets follow
mgcv::predict.gam() semantics. Supported models are gam and bam fits
with a single linear predictor and an ordinary scalar inverse-link mean
(including negative binomial, Tweedie, beta regression and scaled t families).
SCAM fits with supported single-predictor families also support link- and
response-scale differences, with delta or simulation uncertainty and
pointwise or simultaneous intervals. SCAM delta intervals use the local
covariance of transformed coefficients. Gaussian simulation draws
unrestricted fitting coefficients and applies the fitted positivity
transformation; user draws must already be in transformed coordinates and
satisfy the coefficient constraints. MH sampling is unavailable for SCAM
fits, and smoothing-parameter uncertainty is unsupported; use
unconditional = FALSE.
A tibble of class "conditional_differences", with .contrast,
.diff, .se, .lower_ci, .upper_ci, and evaluation covariates.
.se is on the requested scale; for simulation it is the standard deviation
of difference draws. A single comparison factor has .level_1 and
.level_2 columns. Multiple factors have <factor>_1 and <factor>_2
columns. Attributes record by, condition, scale, uncertainty,
ci_level, exclude, interval, simultaneous_scope, and plotting
channels. Simultaneous results also contain .crit, the calibrated
critical value, constant within each coverage set.
load_mgcv() # Simulate group-specific curves with Gaussian noise and fit factor-by smooths df <- data_sim("eg4", n = 300, seed = 2) m <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = df, method = "REML") # Compare fitted responses over x2, including the parametric group effects cd <- conditional_differences(m, by = "fac", condition = "x2") cd draw(cd)load_mgcv() # Simulate group-specific curves with Gaussian noise and fit factor-by smooths df <- data_sim("eg4", n = 300, seed = 2) m <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = df, method = "REML") # Compare fitted responses over x2, including the parametric group effects cd <- conditional_differences(m, by = "fac", condition = "x2") cd draw(cd)
Construct covariate combinations using conditional_values() conventions,
then estimate response moments with fitted_moments(). Other covariates are
held at typical values; observations are not averaged over those covariates.
conditional_moments( model, condition = NULL, data = NULL, moments = c("mean", "variance", "cv"), n_vals = 100, complete = TRUE, ... ) ## S3 method for class 'gam' conditional_moments( model, condition = NULL, data = NULL, moments = c("mean", "variance", "cv"), n_vals = 100, complete = TRUE, ... )conditional_moments( model, condition = NULL, data = NULL, moments = c("mean", "variance", "cv"), n_vals = 100, complete = TRUE, ... ) ## S3 method for class 'gam' conditional_moments( model, condition = NULL, data = NULL, moments = c("mean", "variance", "cv"), n_vals = 100, complete = TRUE, ... )
model |
a fitted GAM object. |
condition |
Character vector or list specifying covariates and optional values. The first covariate supplies the plotting axis, followed by colour, facet columns and facet rows. Grouped surface conditions are not supported. |
data |
optional data frame used to generate condition values and
determine covariate classes. Explicit values in |
moments |
Character vector selecting |
n_vals |
Positive integer; number of values to generate along a numeric plotting axis. Defaults to 100. Explicit condition values or helpers override generated values; other numeric conditions use five-number summaries. |
complete |
logical; if |
... |
Arguments to |
A tibble of class "conditional_moments", with the columns returned
by fitted_moments() and the plotting channels of conditional_values().
load_mgcv() m <- gam(mpg ~ s(wt, k = 5), data = mtcars, method = "REML") conditional_moments(m, condition = "wt", moments = c("mean", "variance")) |> draw()load_mgcv() m <- gam(mpg ~ s(wt, k = 5), data = mtcars, method = "REML") conditional_moments(m, condition = "wt", moments = c("mean", "variance")) |> draw()
Generate predicted values from a GAM, conditional upon supplied values of
covariates. conditional_values() is modelled after
marginaleffects::plot_predictions(), but with an intentionally simpler,
more restrictive functionality. The intended use case is for quickly
visualizing predicted values from a fitted GAM on the response scale. For
more complex model predictions, you are strongly encouraged to use
marginaleffects::plot_predictions().
conditional_values( model, condition = NULL, data = NULL, scale = c("response", "link", "linear_predictor"), ... ) ## S3 method for class 'gam' conditional_values( model, condition = NULL, data = NULL, scale = c("response", "link", "linear_predictor"), n_vals = NULL, ci_level = 0.95, complete = TRUE, ... ) ## S3 method for class 'gamm4' conditional_values(model, ...) ## S3 method for class 'scam' conditional_values(model, ..., unconditional = FALSE)conditional_values( model, condition = NULL, data = NULL, scale = c("response", "link", "linear_predictor"), ... ) ## S3 method for class 'gam' conditional_values( model, condition = NULL, data = NULL, scale = c("response", "link", "linear_predictor"), n_vals = NULL, ci_level = 0.95, complete = TRUE, ... ) ## S3 method for class 'gamm4' conditional_values(model, ...) ## S3 method for class 'scam' conditional_values(model, ..., unconditional = FALSE)
model |
a fitted GAM object. |
condition |
either a character vector or a list supplying the names of
covariates, and possibly their values, to condition on. The order of the
values determines how these are plotted via the |
data |
optional data frame used to generate condition values and
determine covariate classes. Explicit values in |
scale |
character; which scale should predictions be returned on? |
... |
arguments passed to |
n_vals |
positive integer or |
ci_level |
numeric; a number on interval (0,1) giving the coverage for credible intervals. |
complete |
logical; if |
unconditional |
logical; include smoothing parameter uncertainty in the Bayesian covariance matrix, if available. Otherwise a warning is issued and the uncorrected covariance is used. |
A data frame (tibble) of class "conditional_values".
Gavin L. Simpson
load_mgcv() # Simulate an additive Gaussian response and fit a GAM df <- data_sim("eg1", n = 200, seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # Vary x2 while holding the other covariates at representative values cv <- conditional_values(m, condition = "x2") cv draw(cv)load_mgcv() # Simulate an additive Gaussian response and fit a GAM df <- data_sim("eg1", n = 200, seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # Vary x2 while holding the other covariates at representative values cv <- conditional_values(m, condition = "x2") cv draw(cv)
Calculates point-wise confidence or simultaneous intervals for the first derivatives of smooth terms in a fitted GAM.
## S3 method for class 'fderiv' confint( object, parm, level = 0.95, type = c("confidence", "simultaneous"), nsim = 10000, ncores = 1L, ... )## S3 method for class 'fderiv' confint( object, parm, level = 0.95, type = c("confidence", "simultaneous"), nsim = 10000, ncores = 1L, ... )
object |
an object of class |
parm |
which parameters (smooth terms) are to be given intervals as a vector of terms. If missing, all parameters are considered. |
level |
numeric, |
type |
character; the type of interval to compute. One of |
nsim |
integer; the number of simulations used in computing the simultaneous intervals. |
ncores |
number of cores for generating random variables from a
multivariate normal distribution. Passed to |
... |
additional arguments for methods |
a data frame with components:
term; factor indicating to which term each row relates,
lower; lower limit of the confidence or simultaneous interval,
est; estimated derivative
upper; upper limit of the confidence or simultaneous interval.
Gavin L. Simpson
load_mgcv() dat <- data_sim("eg1", n = 1000, dist = "normal", scale = 2, seed = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # new data to evaluate the derivatives at, say over the middle 50% of range # of each covariate middle <- function(x, n = 25, coverage = 0.5) { v <- (1 - coverage) / 2 q <- quantile(x, prob = c(0 + v, 1 - v), type = 8) seq(q[1], q[2], length = n) } new_data <- sapply(dat[c("x0", "x1", "x2", "x3")], middle) new_data <- data.frame(new_data) ## first derivatives of all smooths... fd <- fderiv(mod, newdata = new_data) ## point-wise interval ci <- confint(fd, type = "confidence") ci ## simultaneous interval for smooth term of x2 x2_sint <- confint(fd, parm = "x2", type = "simultaneous", nsim = 10000, ncores = 2 ) x2_sintload_mgcv() dat <- data_sim("eg1", n = 1000, dist = "normal", scale = 2, seed = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # new data to evaluate the derivatives at, say over the middle 50% of range # of each covariate middle <- function(x, n = 25, coverage = 0.5) { v <- (1 - coverage) / 2 q <- quantile(x, prob = c(0 + v, 1 - v), type = 8) seq(q[1], q[2], length = n) } new_data <- sapply(dat[c("x0", "x1", "x2", "x3")], middle) new_data <- data.frame(new_data) ## first derivatives of all smooths... fd <- fderiv(mod, newdata = new_data) ## point-wise interval ci <- confint(fd, type = "confidence") ci ## simultaneous interval for smooth term of x2 x2_sint <- confint(fd, parm = "x2", type = "simultaneous", nsim = 10000, ncores = 2 ) x2_sint
Calculates point-wise confidence or simultaneous intervals for the smooth terms of a fitted GAM.
## S3 method for class 'gam' confint( object, parm, level = 0.95, data = newdata, n = 100, type = c("confidence", "simultaneous"), nsim = 10000, shift = FALSE, transform = FALSE, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, ncores = 1, partial_match = FALSE, ..., newdata = NULL ) ## S3 method for class 'gamm' confint(object, ...) ## S3 method for class 'gamm4' confint(object, ...) ## S3 method for class 'scam' confint( object, parm = smooths(object), ..., unconditional = FALSE, overall_uncertainty = FALSE )## S3 method for class 'gam' confint( object, parm, level = 0.95, data = newdata, n = 100, type = c("confidence", "simultaneous"), nsim = 10000, shift = FALSE, transform = FALSE, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, ncores = 1, partial_match = FALSE, ..., newdata = NULL ) ## S3 method for class 'gamm' confint(object, ...) ## S3 method for class 'gamm4' confint(object, ...) ## S3 method for class 'scam' confint( object, parm = smooths(object), ..., unconditional = FALSE, overall_uncertainty = FALSE )
object |
an object of class |
parm |
which parameters (smooth terms) are to be given intervals as a vector of terms. If missing, all parameters are considered, although this is not currently implemented. |
level |
numeric, |
data |
data frame; new values of the covariates used in the model fit. The selected smooth(s) will be evaluated at the supplied values. |
n |
numeric; the number of points to evaluate smooths at. |
type |
character; the type of interval to compute. One of |
nsim |
integer; the number of simulations used in computing the simultaneous intervals. |
shift |
logical; should the intercept of the smooth's linear predictor
be added to the smooth? Predictors without an intercept are shifted by zero.
Only the intercept is added; other parametric effects, including factor
effects associated with a factor |
transform |
logical; should the smooth be evaluated on a transformed scale? For generalised models, this involves applying the inverse of the link function used to fit the model. Alternatively, the name of, or an actual, function can be supplied to transform the smooth and it's confidence interval. |
unconditional |
logical; if |
frequentist |
logical; if |
overall_uncertainty |
logical; should the uncertainty in the model constant term be included in the standard error of the evaluate values of the smooth? |
ncores |
number of cores for generating random variables from a
multivariate normal distribution. Passed to |
partial_match |
logical; should matching |
... |
additional arguments passed to |
newdata |
DEPRECATED! data frame; containing new values of the covariates used in the model fit. The selected smooth(s) will be evaluated at the supplied values. |
For SCAM fits, confint() returns intervals for smooth functions,
with parm selecting smooth labels. It uses transformed-coefficient
Gaussian uncertainty conditional on the fitted smoothing parameters.
By default, intercept uncertainty is excluded. These intervals do not
enforce shape constraints on their limits.
a tibble with components:
.smooth; character indicating to which term each row relates,
.type; the type of smooth,
.by the name of the by variable if a by smooth, NA otherwise,
one or more vectors of values at which the smooth was evaluated, named as per the variables in the smooth,
zero or more variables containing values of the by variable,
.estimate; estimated value of the smooth,
.se; standard error of the estimated value of the smooth,
.crit; critical value for the 100 * level% confidence interval;
NA for bootstrap limits.
.lower_ci; lower limit of the confidence or simultaneous interval,
.upper_ci; upper limit of the confidence or simultaneous interval,
overall_uncertainty applies to both pointwise and simultaneous
intervals. Each simultaneous band covers the evaluation points of one
fitted smooth by default, or its continuous domain with tube calibration;
separate smooths do not form a joint coverage set.
Native scasm fits default to overall_uncertainty = FALSE and use stored
bootstrap draws for pointwise intervals when available, as in
smooth_estimates(). Shifting and transforming a smooth preserves its
interval limits, including asymmetric bootstrap limits.
Shape-enforced intervals describe unshifted smooth components on the
model scale; shift = TRUE and effect transformations are unsupported.
Gavin L. Simpson
load_mgcv() dat <- data_sim("eg1", n = 1000, dist = "normal", scale = 2, seed = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # new data to evaluate the smooths at, say over the middle 50% of range # of each covariate middle <- function(x, n = 50, coverage = 0.5) { v <- (1 - coverage) / 2 q <- quantile(x, prob = c(0 + v, 1 - v), type = 8) seq(q[1], q[2], length = n) } new_data <- sapply(dat[c("x0", "x1", "x2", "x3")], middle) new_data <- data.frame(new_data) ## point-wise interval for smooth of x2 ci <- confint(mod, parm = "s(x2)", type = "confidence", data = new_data) ciload_mgcv() dat <- data_sim("eg1", n = 1000, dist = "normal", scale = 2, seed = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # new data to evaluate the smooths at, say over the middle 50% of range # of each covariate middle <- function(x, n = 50, coverage = 0.5) { v <- (1 - coverage) / 2 q <- quantile(x, prob = c(0 + v, 1 - v), type = 8) seq(q[1], q[2], length = n) } new_data <- sapply(dat[c("x0", "x1", "x2", "x3")], middle) new_data <- data.frame(new_data) ## point-wise interval for smooth of x2 ci <- confint(mod, parm = "s(x2)", type = "confidence", data = new_data) ci
All combinations of factor levels plus typical values of continuous variables
data_combos(object, ...) ## S3 method for class 'gam' data_combos(object, vars = everything(), complete = TRUE, data = NULL, ...) ## S3 method for class 'gamm4' data_combos(object, ...)data_combos(object, ...) ## S3 method for class 'gam' data_combos(object, vars = everything(), complete = TRUE, data = NULL, ...) ## S3 method for class 'gamm4' data_combos(object, ...)
object |
a fitted model object. |
... |
arguments passed to methods. |
vars |
terms to include or exclude from the returned object. Uses tidyselect principles. |
complete |
logical; should all combinations of factor levels be
returned? If |
data |
an optional data frame supplying covariate classes. By default, these are taken from the stored model frame; typical values come from the fitted model's covariate summaries. |
A tidy reimplementation of the functions implemented in mgcv::gamSim()
that can be used to fit GAMs. The sampling
distribution can be applied to all the example types.
data_sim( model = "eg1", n = 400, scale = NULL, theta = 3, power = 1.5, dist = c("normal", "poisson", "binary", "negbin", "tweedie", "gamma", "ocat", "ordered categorical"), n_cat = 4, cuts = c(-1, 0, 5), seed = NULL, gfam_families = c("binary", "tweedie", "normal"), family = NULL, predictors = NULL, parameters = list(), observation = NULL )data_sim( model = "eg1", n = 400, scale = NULL, theta = 3, power = 1.5, dist = c("normal", "poisson", "binary", "negbin", "tweedie", "gamma", "ocat", "ordered categorical"), n_cat = 4, cuts = c(-1, 0, 5), seed = NULL, gfam_families = c("binary", "tweedie", "normal"), family = NULL, predictors = NULL, parameters = list(), observation = NULL )
model |
character; the name of a model, such as |
n |
numeric; the number of observations to simulate. |
scale |
numeric; for normal responses, the standard deviation; for
Poisson and negative binomial responses, a multiplier of the true
function; for binary responses, a multiplier after subtracting 5; for
Gamma and Tweedie responses, the dispersion. Ignored for ordinal
responses. Legacy numeric vectors are recycled across observations.
Use |
theta |
numeric; the dispersion parameter |
power |
numeric; the Tweedie power parameter. |
dist |
character; a sampling distribution for the response
variable. |
n_cat |
integer; the number of categories for categorical response.
Currently only used for |
cuts |
numeric; vector of cut points on the latent variable, excluding
the end points |
seed |
numeric; the seed for the random number generator. Passed to
|
gfam_families |
character; a vector of distributions to use in
generating data with grouped families for use with |
family |
an instantiated family object, such as |
predictors |
|
parameters |
a named list of natural-scale generating parameters. Parameters fixed in the family constructor are used directly. Fitting starting values are not generating parameters: supply the corresponding entries explicitly. See data_sim_families for names and defaults. |
observation |
|
data_sim() can simulate data from several underlying models of
known true functions. Descriptive names and their original short names
are interchangeable, giving identical output for the same arguments and
seed. The available options currently are:
"additive" or "eg1": a four term additive true model. This is the
classic Gu & Wahba
four univariate term test model. See gw_functions for more details of
the underlying four functions.
"bivariate_surface" or "eg2": a bivariate smooth true model.
"varying_coefficient" or "eg3": an example containing a continuous
by smooth (varying
coefficient) true model. The model is where the function is .
"factor_by" or "eg4": a factor by smooth true model. The true model
contains a factor
with 3 levels, where the response for the nth level follows the nth
Gu & Wahba function (for ).
"additive_factor" or "eg5": an additive plus factor true model. The
response is a linear
combination of the Gu & Wahba functions 2, 3, 4 (the latter is a null
function) plus a factor term with four levels.
"additive_group_effects" or "eg6": an additive model plus four
group intercepts with fixed realised values 3, 6, 9, 12.
"additive_correlated" or "eg7": a version of the model in "eg1",
but where the covariates are
correlated.
"gu_wahba_f2" or "gwf2": a model where the response is Gu & Wahba's
plus noise.
"luo_wahba_f6" or "lwf6": a model where the response is Luo &
Wahba's "example 6"
function plus noise.
"gfam": simulates data for use with GAMs with
family = gfam(families). See example in mgcv::gfam(). If this model
is specified then dist is ignored and gfam_families is used to
specify which distributions are included in the simulated data. Can be a
vector of the distributions allowed by dist, including repeated names.
Defaults use Gaussian standard deviation 0.5, Gamma dispersion 0.5,
Tweedie dispersion 1.5, negative binomial size 3 and Tweedie power 1.5.
Historical grouped ordinal cuts are c(1, 2, 2.5).
Explicit scale, theta, power, n_cat and cuts override these
settings. A supplied scale is the Gaussian standard deviation and the
Gamma or Tweedie dispersion. Identity, logit and log links are used
for normal, binary and positive-mean responses, respectively. Ordinal
responses use a logistic latent variable.
The random component providing noise or sampling variation can follow one
of the distributions, specified via argument dist
"normal": Gaussian,
"poisson": Poisson,
"binary": Bernoulli,
"negbin": Negative binomial,
"tweedie": Tweedie,
"gamma": gamma , and
"ordered categorical": ordered categorical
Other arguments provide the parameters for the distribution.
A tibble containing responses, covariates and true-function columns.
Legacy f is the predictor after its distribution-specific transformation;
component columns retain their original function values. With family,
f is the first linear predictor, y can be a matrix column, and the
"truth" attribute contains eta (all linear predictors), parameters
(natural distribution parameters), functions (the original template),
response (complete responses before censoring), and family. Grouped
families also record index and component-specific parameter lists.
Binomial family objects return proportions and a trials column for
fitting weights. Cox models return observed times and a status column.
An explicit seed restores the caller's RNG state, including its absence;
seed = NULL advances the caller's RNG normally.
Models named "sc_increasing", "sc_decreasing", "sc_convex",
"sc_concave", "sc_positive", "sc_increasing_convex",
"sc_increasing_concave", "sc_decreasing_convex" and
"sc_decreasing_concave" provide univariate reference shapes on [0, 1].
"sc_additive" combines four terms; "sc_tensor" is increasing in two
coordinates; "sc_location_scale" has a concave log-mean and increasing
log dispersion. The latter defaults to family = mgcv::gammals(); other
shape templates default to Gaussian noise with standard deviation 0.2.
See data_sim_shapes for functions, derivatives and mgcv::scasm() recipes.
Gu, C., Wahba, G., (1993). Smoothing Spline ANOVA with Component-Wise Bayesian "Confidence Intervals." J. Comput. Graph. Stat. 2, 97–117.
Luo, Z., Wahba, G., (1997). Hybrid adaptive splines. J. Am. Stat. Assoc. 92, 107–116.
data_sim_families, data_sim_shapes
data_sim("additive", n = 100, seed = 1) # an ordered categorical response data_sim("additive", n = 100, dist = "ocat", n_cat = 4, cuts = c(-1, 0, 5))data_sim("additive", n = 100, seed = 1) # an ordered categorical response data_sim("additive", n = 100, dist = "ocat", n_cat = 4, cuts = c(-1, 0, 5))
data_sim() accepts instantiated standard and mgcv family objects. The
example template supplies covariates and true functions; predictors
supplies the linear predictors; parameters supplies generating values
that are not themselves modelled by a predictor. The "truth" attribute
records all predictors, distribution parameters and complete responses.
The parameter names below belong inside parameters = list(...).
Parameters are scalar unless explicitly described as observation-level.
Beta draws use the constructor's eps endpoint adjustment, matching mgcv's
generator. This adjustment can matter when the beta law places substantial
probability very close to zero or one; eps is recorded in the truth.
| Family | Generating parameters |
gaussian() |
dispersion = 1, the non-negative variance |
poisson(), cpois() |
None |
binomial() |
trials = 1, positive integer trial counts |
Gamma(), inverse.gaussian() |
dispersion = 1 |
nb(), negbin() |
theta, positive size; Inf gives the Poisson limit |
tw(), Tweedie() |
power in (1, 2), and dispersion = 1 |
betar() |
Positive precision |
scat() |
df above the family's min.df, and positive t scale sigma |
ocat() |
Finite increasing cuts, one fewer than the categories |
ziP() |
intercept and natural-scale slope above the constructor's b |
cnorm(), clog() |
Positive sigma, Gaussian SD or logistic scale |
bcg() |
lambda = 0 and positive log-response SD sigma
|
Dispersion and trials can have length one or n. All other scalar-family
parameters are constant across observations. Fixed constructor parameters
are used when available; conflicting explicit parameters are errors.
Otherwise the corresponding generating values are required, including
cut points for ocat(R = ...). For example, both
family = mgcv::nb(theta = 3) and family = mgcv::nb(), parameters = list(theta = 3) specify size 3. Constructor starting values
for an estimated parameter are not used as generating truth. A size range
in negbin(c(1, 10)) also requires an explicit generating theta.
For ziP(), lambda = exp(eta) and
P(Y > 0) = 1 - exp(-exp(intercept + slope * eta)).
Positive observations follow a Poisson distribution conditioned on being
positive. The natural slope includes the constructor's lower bound b;
the second entry of ziP(theta = ...) is instead a log excess above b.
For fixed ordinal spacings, mgcv fixes the first cut at -1; for example
ocat(theta = c(1, 5)) supplies cuts c(-1, 0, 5).
For free cuts whose first value is a, mgcv's fixed first cut of -1
represents the same probabilities after shifting the predictor by -(a + 1).
Include the corresponding component intercept in grouped fitting recipes.
Quasi families do not define a complete sampling distribution and are rejected. Nonzero Box-Cox powers are currently rejected: some Gaussian transformed responses would lie outside the inverse transformation's domain.
The columns returned by predictors follow mgcv's order and links, including
their constructor-specific bounds. These are link-scale predictors, not
the mu arguments of mgcv's random-number generators.
| Family | Predictor order and natural parameters recorded in truth |
gaulss() |
Mean, SD predictor; records mu, sigma |
gammals() |
Log mean, log-dispersion predictor; records mu, dispersion |
gumbls() |
Location, log-scale predictor; records location, mu (mean), sigma |
gevlss() |
Location, log scale, shape predictor; records location, sigma, shape |
shash() |
Location, scale predictor, skewness, log tail; records location, sigma, skewness, tail |
twlss() |
Mean predictor, power predictor, log dispersion; records mu, power, dispersion |
ziplss() |
Log Poisson intensity, complementary log-log presence predictor; records lambda, presence |
multinom(K) |
K logits relative to category 0; records category probabilities |
mvn(d) |
d response means; parameters$covariance defaults to the identity matrix
|
These families need no scalar generating parameters except mvn()'s
optional positive definite covariance matrix. In shash(), the transformed
normal is multiplied by tail * sigma, following mgcv's parameterisation.
In gumbls(), the mean is location plus Euler's constant times sigma;
the first predictor specifies the location. For gevlss(), the default
shape link restricts shape to (-1, 0.5); the identity link allows any finite
shape. In ziplss(), positive counts follow a zero-truncated Poisson distribution.
Let g be the template's f before distribution transformations. Scalar
Gaussian, t, Gaussian-censoring, logistic-censoring and Box-Cox families use
natural location g. Binomial and beta means are plogis((g - 5) / 5);
ordinal location is g - mean(g); the ziP() predictor is g / 5.
Other scalar means are exp(g / 5). Each mean is transformed with the
supplied family's link. If it is outside that link's domain, supply custom
predictors rather than relying on a default.
For general families, default predictors are: (g, 0) for gaulss() and
gumbls(); (g / 5, 0) for gammals() and ziplss();
(g, 0, linkfun(0)) for gevlss() (zero shape under the supplied shape link);
(g, 0, 0, 0) for shash(); and (g / 5, 0, 0) for twlss().
Multivariate normal means repeat g. Multinomial logit j is
(g - mean(g)) / 5 * j / K. The sc_location_scale template instead
supplies its own log mean and log dispersion for gammals().
For cnorm(), clog(), cpois() and bcg(), observation can contain
finite left and right detection limits and a positive interval_width.
Responses outside detection limits are left or right censored. Other
responses are placed in rounding intervals wholly inside those limits;
values in intervals crossing a limit are retained exactly. Omitting
observation returns complete responses.
Matrix responses use equal entries for exact observations, (limit, -Inf)
for left censoring, (limit, Inf) for right censoring, and (lower, upper)
for intervals. bcg() instead uses zero in the second entry for left
censoring; its limits must be positive. Poisson detection limits must be
non-integer, and interval widths must be integer numbers of counts. Its
intervals use half-integer endpoints to avoid ambiguity at count values.
cox.ph() uses Weibull cumulative baseline hazard
H0(t) = (t / baseline_scale)^baseline_shape, with both baseline parameters
defaulting to 1. Event times have survival exp(-H0(t) * exp(eta)).
Independent exponential censoring has censor_rate = 0.2; zero disables
censoring. Default eta is (g - mean(g)) / 5. Fit using weights = status.
True event and censoring times are retained in the truth parameter list.
Supply family = mgcv::gfam(list(...)), optionally with
parameters = list(components = list(...), index = ...). components
contains one parameter list per family-list position. index is one
integer position per row (a scalar selects the same family for every row).
Without index, every component is represented at least once and remaining
positions are sampled uniformly; n must be at least the number of families.
Repeated family types retain separate indices and parameters.
The default shared predictor is g / 5; custom predictors return one column.
Scalar response families are supported; general families are rejected.
Censored-family components return complete, uncensored responses. Fit using
cbind(y, index) as the response and weights = trials if a component is
binomial with more than one trial. Row-level dispersion and trial vectors
in component parameter lists align with the full generated data, or can
have the component's row count. Truth parameters record each component's rows.
data_sim(), data_sim_shapes, mgcv::family.mgcv()
# A beta response: precision is explicitly chosen, rather than estimated. d <- data_sim(family = mgcv::betar(theta = 12), seed = 2) attr(d, "truth")$parameters$precision # Binomial proportions: use trials as the fitting weights. d <- data_sim(family = binomial(), parameters = list(trials = 10), seed = 2) # Mean and standard deviation have separate predictors. d <- data_sim("gwf2", family = mgcv::gaulss(), seed = 2, predictors = function(d) cbind(d$f, log(0.2 + d$x))) # Fit a censored normal model to the matrix response. d <- data_sim("sc_increasing", family = mgcv::cnorm(theta = 0.2), seed = 2, observation = list(left = 0.1, right = 0.9)) m <- mgcv::gam(y ~ s(x), family = mgcv::cnorm(), data = d, method = "REML")# A beta response: precision is explicitly chosen, rather than estimated. d <- data_sim(family = mgcv::betar(theta = 12), seed = 2) attr(d, "truth")$parameters$precision # Binomial proportions: use trials as the fitting weights. d <- data_sim(family = binomial(), parameters = list(trials = 10), seed = 2) # Mean and standard deviation have separate predictors. d <- data_sim("gwf2", family = mgcv::gaulss(), seed = 2, predictors = function(d) cbind(d$f, log(0.2 + d$x))) # Fit a censored normal model to the matrix response. d <- data_sim("sc_increasing", family = mgcv::cnorm(theta = 0.2), seed = 2, observation = list(left = 0.1, right = 0.9)) m <- mgcv::gam(y ~ s(x), family = mgcv::cnorm(), data = d, method = "REML")
data_sim() supplies analytic reference functions for mgcv::scasm().
All covariates are uniform on [0, 1]. Univariate templates return f1, the
true function, and its analytic derivatives d1 and d2. The response
contains sampling variation; the derivative columns describe the truth.
Model suffix after sc_ |
Function | xt in s(x, bs = "sc", xt = ...) |
increasing |
plogis(8 * (x - 0.5)) |
"m+" |
decreasing |
1 - plogis(8 * (x - 0.5)) |
"m-" |
convex |
(x - 0.5)^2 |
"c+" |
concave |
1 - (x - 0.5)^2 |
"c-" |
positive |
0.2 + exp(-16 * (x - 0.5)^2) |
"+", with no intercept |
increasing_convex |
exp(2 * x) / exp(2) |
c("m+", "c+") |
increasing_concave |
log1p(4 * x) / log(5) |
c("m+", "c-") |
decreasing_convex |
exp(-2 * x) |
c("m-", "c+") |
decreasing_concave |
1 - x^2 |
c("m-", "c-")
|
Remove the intercept for the positivity recipe so the constrained smooth represents the whole function. An unconstrained intercept combined with a centred smooth does not express the same positivity requirement.
sc_additive adapts mgcv's example. Its raw terms are gw_f0(x0),
2 * plogis(20 * (x1 - 0.4)), gw_f2(x2) and 10 * (x3 - 0.55)^4.
The true predictor is their sum minus 1, divided by 4. The second term is
increasing and the fourth is convex. Use predictors = function(d) d$f
with family = poisson() to sample mgcv's Poisson example.
sc_tensor uses f = x + z + x * z, increasing in both covariates. Its
dx and dz columns give the true partial derivatives.
sc_location_scale uses log mean sin(pi * x) / 2 and log dispersion
-2 + z, returned in f and f_scale. It defaults to gammals() and
records derivatives in d1, d2 and d_scale. Constraints act on the
specified predictors; in particular the concavity concerns the log mean.
The recipes use the default bs = 0 for fitting without bootstrap
replicates. To obtain native constraint-respecting bootstrap coefficient
draws, fit with a positive bs, such as bs = 100.
data_sim(), data_sim_families, mgcv::scasm()
load_mgcv() d <- data_sim("sc_increasing", n = 200, seed = 2) m <- scasm(y ~ s(x, bs = "sc", xt = "m+", k = 8), data = d) d <- data_sim("sc_positive", n = 200, seed = 2) m <- scasm(y ~ s(x, bs = "sc", xt = "+", k = 8) - 1, data = d) d <- data_sim("sc_additive", n = 240, family = poisson(), seed = 2, predictors = function(d) d$f) m <- scasm(y ~ s(x0, k = 6) + s(x1, bs = "sc", xt = "m+", k = 6) + s(x2, k = 6) + s(x3, bs = "sc", xt = "c+", k = 6), family = poisson(), data = d) d <- data_sim("sc_tensor", seed = 2) m <- scasm(y ~ te(x, z, bs = c("sc", "sc"), xt = list("m+", "m+"), k = c(6, 6)), data = d) d <- data_sim("sc_location_scale", seed = 2) m <- scasm(list(y ~ s(x, bs = "sc", xt = "c-"), ~s(z, bs = "sc", xt = "m+")), family = gammals(), data = d)load_mgcv() d <- data_sim("sc_increasing", n = 200, seed = 2) m <- scasm(y ~ s(x, bs = "sc", xt = "m+", k = 8), data = d) d <- data_sim("sc_positive", n = 200, seed = 2) m <- scasm(y ~ s(x, bs = "sc", xt = "+", k = 8) - 1, data = d) d <- data_sim("sc_additive", n = 240, family = poisson(), seed = 2, predictors = function(d) d$f) m <- scasm(y ~ s(x0, k = 6) + s(x1, bs = "sc", xt = "m+", k = 6) + s(x2, k = 6) + s(x3, bs = "sc", xt = "c+", k = 6), family = poisson(), data = d) d <- data_sim("sc_tensor", seed = 2) m <- scasm(y ~ te(x, z, bs = c("sc", "sc"), xt = list("m+", "m+"), k = c(6, 6)), data = d) d <- data_sim("sc_location_scale", seed = 2) m <- scasm(list(y ~ s(x, bs = "sc", xt = "c-"), ~s(z, bs = "sc", xt = "m+")), family = gammals(), data = d)
Prepare a data slice through model covariates
data_slice(object, ...) ## Default S3 method: data_slice(object, ...) ## S3 method for class 'data.frame' data_slice(object, ..., .observed_only = FALSE, .by = NULL) ## S3 method for class 'gam' data_slice( object, ..., data = NULL, envir = NULL, .observed_only = FALSE, .by = NULL ) ## S3 method for class 'gamm' data_slice(object, ...) ## S3 method for class 'gamm4' data_slice(object, ...) ## S3 method for class 'scam' data_slice(object, ...)data_slice(object, ...) ## Default S3 method: data_slice(object, ...) ## S3 method for class 'data.frame' data_slice(object, ..., .observed_only = FALSE, .by = NULL) ## S3 method for class 'gam' data_slice( object, ..., data = NULL, envir = NULL, .observed_only = FALSE, .by = NULL ) ## S3 method for class 'gamm' data_slice(object, ...) ## S3 method for class 'gamm4' data_slice(object, ...) ## S3 method for class 'scam' data_slice(object, ...)
object |
an R model object. |
... |
< |
.observed_only |
logical or character; should the data slice be trimmed
to those combinations of the variables specified that are observed in
|
.by |
< |
data |
an alternative data frame of values containing all the variables
needed to fit the model. If |
envir |
the environment within which to recreate the data used to fit
|
A data slice is the data set that results where one (or more covariates) is varied systematically over some or all of its (their) range or at a specified subset of values of interest, while any remaining covariates in the model are held at fixed, representative values. This is known as a reference grid in package emmeans and a data grid in the marginaleffects package.
For GAMs, any covariates not specified via ... will take representative
values determined from the data used to fit the model as follows:
for numeric covariates, the value in the fitting data that is closest to the median value is used,
for factor covariates, the modal (most frequently observed) level is used,
or the first level (sorted as per the vector returned by base::levels()
if several levels are observed the same number of times.
These values are already computed when calling gam() or bam() for example
and can be found in the var.summary component of the fitted model. Function
typical_values() will extract these values for you if you are interested.
Convenience functions evenly(), ref_level(), and level() are provided
to help users specify data slices. ref_level(), and level() also ensure
that factor covariates have the correct levels, as needed by
mgcv::predict.gam() for example.
For an extended discussion of data_slice() and further examples, see
vignette("data-slices", package = "gratia").
With .by, unspecified covariates retain their overall representative
values. Specify an expression such as z = mean(z) to use a group-specific
value instead. Factor levels and ordered status are preserved, and the result
is an ungrouped tibble. .observed_only filters exact matches within each
group; interpolated values need not match observed values.
Grouping limits the default range of evenly() to each group's marginal
range. It does not ensure joint support for multiple continuous covariates.
Explicit values or lower and upper bounds can still request extrapolation.
The convenience functions evenly(), ref_level(), and level().
typical_values() for extracting the representative values used for
covariates in the model but not named in the slice.
load_mgcv() # simulate some Gaussian data df <- data_sim("eg1", n = 50, seed = 2) # fit a GAM with 1 smooth and 1 linear term m <- gam(y ~ s(x2, k = 7) + x1, data = df, method = "REML") # Want to predict over f(x2) while holding `x1` at some value. # Default will use the observation closest to the median for unspecified # variables. ds <- data_slice(m, x2 = evenly(x2, n = 50)) ds # for full control, specify the values you want ds <- data_slice(m, x2 = evenly(x2, n = 50), x1 = 0.3) # or provide an expression (function call) which will be evaluated in the # data frame passed to `data` or `model.frame(object)` ds <- data_slice(m, x2 = evenly(x2, n = 50), x1 = mean(x1))load_mgcv() # simulate some Gaussian data df <- data_sim("eg1", n = 50, seed = 2) # fit a GAM with 1 smooth and 1 linear term m <- gam(y ~ s(x2, k = 7) + x1, data = df, method = "REML") # Want to predict over f(x2) while holding `x1` at some value. # Default will use the observation closest to the median for unspecified # variables. ds <- data_slice(m, x2 = evenly(x2, n = 50)) ds # for full control, specify the values you want ds <- data_slice(m, x2 = evenly(x2, n = 50), x1 = 0.3) # or provide an expression (function call) which will be evaluated in the # data frame passed to `data` or `model.frame(object)` ds <- data_slice(m, x2 = evenly(x2, n = 50), x1 = mean(x1))
Posterior expectations of derivatives from an estimated model
## S3 method for class 'gamm4' derivative_samples(model, ...) derivative_samples(model, ...) ## Default S3 method: derivative_samples(model, ...) ## S3 method for class 'gamm' derivative_samples(model, ...) ## S3 method for class 'gam' derivative_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, focal = NULL, order = 1L, type = c("forward", "backward", "central"), scale = c("response", "linear_predictor"), n_grid = 200L, eps = NULL, envir = environment(formula(model)) ) ## S3 method for class 'scam' derivative_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, focal = NULL, order = 1L, type = c("forward", "backward", "central"), scale = c("response", "linear_predictor"), n_grid = 200L, eps = NULL, envir = environment(formula(model)) )## S3 method for class 'gamm4' derivative_samples(model, ...) derivative_samples(model, ...) ## Default S3 method: derivative_samples(model, ...) ## S3 method for class 'gamm' derivative_samples(model, ...) ## S3 method for class 'gam' derivative_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, focal = NULL, order = 1L, type = c("forward", "backward", "central"), scale = c("response", "linear_predictor"), n_grid = 200L, eps = NULL, envir = environment(formula(model)) ) ## S3 method for class 'scam' derivative_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, focal = NULL, order = 1L, type = c("forward", "backward", "central"), scale = c("response", "linear_predictor"), n_grid = 200L, eps = NULL, envir = environment(formula(model)) )
model |
a fitted model to compute derivative samples for |
... |
arguments passed to other methods and on to |
data |
a data frame containing the values of the model covariates at which to evaluate derivatives of fitted values. If supplied, all but one variable must be held at a constant value. |
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
chains |
positive integer or |
seed |
numeric or |
method |
character; which algorithm to use to sample from the posterior.
Currently implemented methods are: |
n_cores |
positive integer; maximum concurrent MH chains using mirai,
capped at |
n_threads |
positive integer; threads within Gaussian sampling using mvnfast. Defaults to one. This is separate from concurrent MH chains. |
burnin |
numeric; the length of any initial burn in period to discard.
See |
thin |
positive integer; retain every |
t_df |
numeric; degrees of freedom for static multivariate t proposal.
See |
rw_scale |
numeric; factor by which to scale posterior covariance
matrix when generating random walk proposals. See |
frequentist |
logical; if |
unconditional |
logical; if |
draws |
matrix; user supplied posterior draws to be used when
|
diagnostics |
logical; calculate coefficient R-hat, effective sample sizes, and Monte Carlo standard errors using the optional posterior package. |
mh_backend |
character; |
mvn_method |
character; one of |
block_size |
positive integer; maximum observation rows per block in the gratia MH evaluator. Large designs are evaluated without storing a full matrix. |
dense_limit |
numeric; maximum number of design-matrix elements to cache for the gratia MH backend. Use zero to force blockwise evaluation. |
focal |
character; name of the focal variable. The response derivative of the response with respect to this variable will be returned. All other variables involved in the model will be held at constant values. This must be supplied. |
order |
numeric; the order of derivative. |
type |
character; the type of finite difference used. One of
|
scale |
character; should the derivative be estimated on the response
or the linear predictor (link) scale? One of |
n_grid |
positive integer; resolution for constructing evaluation data if
|
eps |
a positive finite number giving the absolute finite-difference
step, or |
envir |
the environment within which to recreate the data used to fit
|
For LSS models, response-scale derivatives differentiate the expected response
returned by fitted_samples(), retaining the joint uncertainty in every
parameter that affects that expectation. Predictor-scale derivatives refer
to the first linear predictor. Smooth-component derivatives and derivatives
of the response expectation are different quantities.
Rows with unavailable required covariates retain NA derivatives by
default; explicit na.action requests follow response_derivatives().
Non-finite derivative calculations at available rows raise an error,
including when only some coefficient draws are affected. Response-scale
derivatives require an existing response mean; scaled t families need
fitted degrees of freedom greater than one.
A tibble, currently with the following variables:
.derivative: the estimated partial derivative,
additional columns containing the covariate values at which the derivative was evaluated.
Gavin L. Simpson
load_mgcv() df <- data_sim("eg1", dist = "negbin", scale = 0.25, seed = 42) # fit the GAM (note: for execution time reasons using bam()) m <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, family = nb(), method = "fREML") # data slice through data along x2 - all other covariates will be set to # typical values (value closest to median) ds <- data_slice(m, x2 = evenly(x2, n = 200)) # samples from posterior of derivatives fd_samp <- derivative_samples(m, data = ds, type = "central", focal = "x2", eps = 0.01, seed = 21, n_draws = 100 ) # plot the first 20 posterior draws if (requireNamespace("ggplot2") && requireNamespace("dplyr")) { library("ggplot2") fd_samp |> dplyr::filter(.draw <= 20) |> ggplot(aes(x = x2, y = .derivative, group = .draw)) + geom_line(alpha = 0.5) }load_mgcv() df <- data_sim("eg1", dist = "negbin", scale = 0.25, seed = 42) # fit the GAM (note: for execution time reasons using bam()) m <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, family = nb(), method = "fREML") # data slice through data along x2 - all other covariates will be set to # typical values (value closest to median) ds <- data_slice(m, x2 = evenly(x2, n = 200)) # samples from posterior of derivatives fd_samp <- derivative_samples(m, data = ds, type = "central", focal = "x2", eps = 0.01, seed = 21, n_draws = 100 ) # plot the first 20 posterior draws if (requireNamespace("ggplot2") && requireNamespace("dplyr")) { library("ggplot2") fd_samp |> dplyr::filter(.draw <= 20) |> ggplot(aes(x = x2, y = .derivative, group = .draw)) + geom_line(alpha = 0.5) }
Derivatives of estimated smooths via finite differences
derivatives(object, ...) ## Default S3 method: derivatives(object, ...) ## S3 method for class 'gamm' derivatives(object, ...) ## S3 method for class 'gam' derivatives( object, select = NULL, term = deprecated(), data = newdata, order = 1L, type = c("forward", "backward", "central"), n = 100, eps = NULL, interval = c("confidence", "simultaneous"), n_sim = 10000, level = 0.95, unconditional = FALSE, frequentist = FALSE, offset = NULL, ncores = 1, partial_match = FALSE, ..., newdata = NULL, envir = NULL, wrt = c("smooth", "covariate"), focal = NULL, interval_method = c("auto", "gaussian", "bootstrap"), simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list() ) ## S3 method for class 'gamm4' derivatives(object, ...) ## S3 method for class 'scam' derivatives(object, ..., unconditional = FALSE)derivatives(object, ...) ## Default S3 method: derivatives(object, ...) ## S3 method for class 'gamm' derivatives(object, ...) ## S3 method for class 'gam' derivatives( object, select = NULL, term = deprecated(), data = newdata, order = 1L, type = c("forward", "backward", "central"), n = 100, eps = NULL, interval = c("confidence", "simultaneous"), n_sim = 10000, level = 0.95, unconditional = FALSE, frequentist = FALSE, offset = NULL, ncores = 1, partial_match = FALSE, ..., newdata = NULL, envir = NULL, wrt = c("smooth", "covariate"), focal = NULL, interval_method = c("auto", "gaussian", "bootstrap"), simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list() ) ## S3 method for class 'gamm4' derivatives(object, ...) ## S3 method for class 'scam' derivatives(object, ..., unconditional = FALSE)
object |
an R object to compute derivatives for. |
... |
arguments passed to other methods. |
select |
character; select which smooth's posterior to draw from.
The default ( |
term |
|
data |
a data frame containing the values of the model covariates at which to evaluate the first derivatives of the smooths. |
order |
numeric; the order of derivative. |
type |
character; the type of finite difference used. One of
|
n |
numeric; the number of points to evaluate the derivative at. |
eps |
a positive finite number giving the absolute finite-difference
step, or |
interval |
character; the type of interval to compute. One of
|
n_sim |
integer; the number of simulations used in computing the simultaneous intervals. |
level |
numeric; |
unconditional |
logical; use smoothness selection-corrected Bayesian covariance matrix? |
frequentist |
logical; use the frequentist covariance matrix? |
offset |
numeric; a value to use for any offset term |
ncores |
number of cores for generating random variables from a
multivariate normal distribution. Passed to |
partial_match |
logical; should smooths be selected by partial matches
with |
newdata |
Deprecated: use |
envir |
optional environment for functions and constants in model
expressions; see |
wrt |
differentiation coordinate: |
focal |
name of the differentiation coordinate, or a vector with one name per selected smooth. For raw-covariate derivatives it must be supplied when a smooth depends on multiple raw inputs. A single name can be used for all selected univariate smooths. |
interval_method |
character; use stored scasm bootstrap draws for
pointwise intervals with |
simultaneous_method |
character; calibration for simultaneous bands.
The default, |
simultaneous_domain |
numeric pair of increasing finite endpoints, or
a named list of such pairs keyed by spline coordinate. For tube bands,
|
tube_control |
named list controlling numerical tube calibration:
|
A tibble, currently with the following variables:
.smooth: the smooth each row refers to,
.by: the name of any factor by variable involved in the smooth,
.fs: the name of any random factor variable involved in the smooth,
.derivative: the estimated derivative,
.se: the standard error of the estimated derivative,
.crit: the critical value such that .derivative ± (.crit * .se) gives
the upper and lower bounds of the requested confidence or simultaneous
interval (given level); NA for bootstrap limits,
.lower_ci: the lower bound of the confidence or simultaneous interval,
.upper_ci: the upper bound of the confidence or simultaneous interval.
plus one or more columns of data containing the values of covariates at which the derivative was evaluated.
With mirai and carrier installed, configure workers with
mirai::daemons() to distribute calculations across selected smooths.
difference_smooths() distributes factor-level comparisons instead.
Without configured workers, or with only one calculation, evaluation is
serial. These functions leave the caller's worker pool running.
Model selection, evaluation of model expressions and random draws are
prepared in the caller. Workers receive the coordinates and coefficient
columns needed for their calculation. Custom prediction methods are evaluated
in the caller, including custom tensor margins and factor-smooth bases;
workers receive their prediction matrices. Simultaneous intervals use successive
draws in selection order, so set.seed() gives the same results with or
without workers, independently of their number or completion order.
derivatives() uses set.seed(); the other functions also accept seed,
which restores the caller's random number state on exit.
smooth_samples() draws coefficients jointly once, then reuses those draws
for every smooth, preserving dependence and chain identities. Sampling
finishes before smooth calculations start, so MH chains and smooth workers
are not nested. Sampling thread controls keep their existing meanings.
Workers use their configured BLAS thread settings; when using a threaded
BLAS, limit its threads before starting daemons to avoid competing threads.
Parallel work is most useful for expensive bases or interval calculations. Small grids can be slower because of transfer and scheduling costs. Large grids and many draws also require memory for worker inputs and returned results, in addition to the final output.
derivatives() will ignore any random effect smooths it encounters in
object.
Gavin L. Simpson
difference_smooths() to compute derivatives of differences
between factor-by smooths with order = 1 or order = 2.
load_mgcv() dat <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 42) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") ## first derivatives of all smooths using central finite differences derivatives(mod, type = "central") if (requireNamespace("mirai", quietly = TRUE) && requireNamespace("carrier", quietly = TRUE)) { library("mirai") library("gratia") local({ mirai::daemons(2) on.exit(mirai::daemons(0)) derivatives(mod, type = "central") }) } ## derivatives for a selected smooth derivatives(mod, type = "central", select = "s(x1)") ## or via a partial match derivatives(mod, type = "central", select = "x1", partial_match = TRUE)load_mgcv() dat <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 42) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") ## first derivatives of all smooths using central finite differences derivatives(mod, type = "central") if (requireNamespace("mirai", quietly = TRUE) && requireNamespace("carrier", quietly = TRUE)) { library("mirai") library("gratia") local({ mirai::daemons(2) on.exit(mirai::daemons(0)) derivatives(mod, type = "central") }) } ## derivatives for a selected smooth derivatives(mod, type = "central", select = "s(x1)") ## or via a partial match derivatives(mod, type = "central", select = "x1", partial_match = TRUE)
Calculate DHARMa-style residuals using gratia's fitted response generators. No DHARMa or mgcViz installation is needed.
dharma_residuals(model, n = 250L, seed = NULL, conditioning = NULL, ...)dharma_residuals(model, n = 250L, seed = NULL, conditioning = NULL, ...)
model |
a fitted model supported by diagnostic_support, with a generator for comparable scalar responses. |
n |
positive integer; number of response datasets to simulate. |
seed |
integer or |
conditioning |
character or |
... |
model-specific diagnostic options, including sdmTMB's |
For each observation, calculate the fractions of simulated responses strictly below it and below or equal to it. The residual is sampled uniformly between these fractions when simulations tie with the observation. Without ties it is the fraction strictly below the observation. This implements DHARMa's PIT idea internally, using gratia's response distributions and conditioning rules.
Residuals lie in [0, 1]. An observation below every simulated response has
residual zero; one above every simulated response has residual one. Endpoints
are retained. Increasing n improves the resolution of the empirical CDF.
Continuous responses without ties have residuals on the grid 0:n / n.
Responses are generated together to retain any modelled dependence. When only marginal response draws are available, these residuals describe the marginal distributions. Censored observations and multivariate responses are unsupported. Binomial successes and failures are compared as proportions with the model's fitting trial counts. A response CDF and finite response moments are not required.
Use type = "dharma" and n_dharma in diagnostic plots. QQ and worm plots
use uniform reference quantiles. Independent responses have approximate
pointwise order-statistic bands: the finite simulation grid means the
continuous uniform reference is approximate. Bands are omitted for dependent
responses because independence-based intervals do not describe their order
statistics. These checks use fitted parameters without refitting the model.
An explicit seed preserves the caller's random-number state. With
seed = NULL, simulation and tie randomisation advance the current state.
A numeric vector in observation order. With na.exclude, excluded
observations are restored as NA; with na.omit, only fitting rows remain.
Hartig, F. DHARMa: Residual Diagnostics for Hierarchical (Multi-Level / Mixed) Regression Models. doi:10.32614/CRAN.package.DHARMa.
appraise(), qq_plot(), worm_plot(), quantile_residuals()
fit <- mgcv::gam(count ~ spray, family = poisson(), data = InsectSprays, method = "REML") head(dharma_residuals(fit, n = 250, seed = 42)) appraise(fit, type = "dharma", n_dharma = 250, seed = 42)fit <- mgcv::gam(count ~ spray, family = poisson(), data = InsectSprays, method = "REML") head(dharma_residuals(fit, n = 250, seed = 42)) appraise(fit, type = "dharma", n_dharma = 250, seed = 42)
Diagnostics use each model's fitted response distribution, observation order and choice of conditioning. The same calculations then produce residuals, reference values and plots across fitting packages.
A conditional check holds fitted random effects fixed. A marginal check averages over their fitted distribution. When responses share random effects or residual correlation, they must be simulated together to preserve that dependence; this is called joint response simulation below. Whether responses are independent depends on the chosen conditioning, not just the model class.
PIT means probability integral transform: the fitted cumulative distribution
function (CDF) maps each observation to a probability. At discrete values,
that probability is randomised over the corresponding probability mass.
Quantile residuals transform PIT values to standard-normal scores.
Surrogate residuals for mgcv::ocat() models transform the same randomised
probabilities to logistic scores. Their reference has location zero and
scale one, and fitting weights do not rescale it. They hold fitted random
effects fixed and use the same observation alignment and seed conventions.
For mgcv::multinom() GAMs, surrogate residuals are vectors of centred
Gumbel utility errors, one for every category including 0, following Cheng,
Wang and Zhang (2021). Conditional utility draws preserve category identity
and are shared across ordinary and scalable panels. Each component has its
own QQ/worm reference and pointwise bands; residual panels use that category's
fitted probability, and covariate panels separate categories.
Select them explicitly with type = "surrogate"; see surrogate_residuals().
A posterior predictive check (PPC) compares observed responses with simulated
data sets that also include approximate uncertainty in fitted parameters.
This table applies to the supported response families described below.
| Fitter | PIT/quantile | Uniform QQ | Simulated QQ | Scalable plots | PPC |
| lm/glm | Yes | Yes | Yes | Yes | Approximate coefficient draws |
| mgcv::gam | Yes | Depends on family | Yes | Yes | Coefficients drawn together |
| mgcv::bam | Marginal families | Marginal or joint | Gaussian AR1; otherwise marginal for GEE | Yes | Excludes GEE AR1 |
| gamm/nlme::lme | Conditional/marginal | Depends on independence | Gaussian; PQL limits | Yes | Gaussian; approximate PQL without residual correlation |
| gamm4/lme4::merMod | Conditional/marginal | Depends on independence | Joint, including GLMMs | Yes | Conditional/marginal |
| glmmTMB | Conditional/marginal | Depends on independence | Joint, including non-Gaussian | Yes | Conditional/marginal |
| GJRM::gamlss | Supported univariate families | Yes | Yes | Yes | Coefficients drawn together |
| GJRM::gjrm | Per-response families | Per response | Per response | Yes | No |
| sdmTMB | Depends on treatment of fields | Depends on independence | Joint, including delta | Yes | Parameters and fields drawn together |
lm/glm: weighted Gaussian and supported response families, with their
fitted dispersion. Quasi families do not specify a response distribution,
so they do not support PIT/quantile residuals or PPCs.
gam/bam: ordinary, distributional and grouped families, including
weighted Gamma, inverse Gaussian, twlss, ordinal and ziP distributions.
Multivariate-normal PITs check each response separately; simulations retain
covariance between responses. Multinomial PIT/quantile residuals accumulate
category probabilities in mgcv's numeric coding order, 0, ..., K.
Nominal multinomial GAMs also support utility surrogate residuals in
ordinary and scalable plots. Utility residuals need no ordering of
categories. Traditional residual checks and PPCs remain available.
SCAM models support ordinary and scalable posterior predictive plots for
supported response families.
Smoothing-parameter uncertainty is not currently supported for SCAM models;
use unconditional = FALSE.
gamm/gamm4 and direct lme/merMod fits use their full predictors.
Gaussian nlme variance weights and residual covariance are retained.
Non-Gaussian gamm fits use penalized quasi-likelihood (PQL). Without residual
correlation, these support approximate response checks and PPCs based on
their fitted working parameters. PQL residual correlation acts on the
working response used for fitting; it does not specify a joint distribution
for the observed responses.
glmmTMB: conditional Gaussian, Poisson, binomial, NB1/NB2, beta, Gamma,
Tweedie, lognormal and supported truncated distributions, including fitted
zero inflation and dispersion. Marginal simulations also provide reference
samples for other families that glmmTMB can simulate. Unsupported conditional
family CDFs remain unavailable. The package's own joint simulator preserves
temporal AR1, spatial covariance and correlated random slopes.
Univariate GJRM::gamlss: uncensored N, LN, GA, GAi, P, NBI, NBII,
BE, LO, WEI, IG, GU and rGU. These include beta, logistic, Weibull,
inverse Gaussian and both Gumbel orientations. GAi is accepted by the
diagnostic adapter, but some GJRM versions do not offer it in gamlss().
Probabilities use the final likelihood parameters. This corrects stored NBII
probabilities that use a Poisson CDF in some upstream versions. Other
families, censored and survival models are not supported by this adapter.
PIT/quantile, response, Pearson and DHARMa-style residuals are available
for all these families. Deviance residuals are available for N, GA, GAi
and P only. Quantile QQ plots use method = NULL or "normal"; PIT and
DHARMa-style QQ plots require method = NULL. Response and Pearson QQ
plots support inverse-CDF ("uniform"), simulated ("simulate"), normal
approximation ("normal") and pooled marginal ("marginal") references.
Observed-versus-fitted panels use response means, including the Weibull
and Gumbel corrections. Residuals are plotted against the first predictor,
which controls Weibull scale or logistic/Gumbel location in those families.
Posterior predictive checks draw both equations' coefficients together,
including beta's logit-linked scale parameter.
Joint GJRM::gjrm: ordinary uncensored bivariate models and ordinary
trivariate binary models support checks of each response distribution.
Supported margins are the univariate GJRM families listed above and binary
responses with probit, logit or complementary log-log links. Each response
uses the final fitted parameters from the joint model.
A supported response can be selected even if another margin is unsupported.
With a fixed seed, selected-response residuals and reference simulations
match the same response in an all-response call.
appraise() returns four panels, each faceted by response. Standalone
diagnostic plots retain these response groups, including when both
responses have the same family. Use response to select one response.
These checks assess the marginal response distributions. Copula checks,
joint response simulation and posterior predictive checks are unavailable.
Selection, switching, ordinal, fixed-margin, censored and survival models are not
supported by these diagnostic methods.
Diagnostics also reject models that use a modeled response in another
response's mean formula or in an auxiliary formula. The complete set of
reference simulations and appraisal panels requires conditioning through
the fitted copula, which these methods do not provide. Smooth plots remain
available.
sdmTMB: supported single-response and delta families retain spatial,
spatiotemporal, grouping, time-varying and smooth effects. Standard deltas
and deltas with the coupled Poisson link support checks of the complete
response, occurrence and positive component. sdmTMB's transformations from
internal parameters to response parameters must be available.
Student-t checks use the fitted location, scale and fixed or estimated
degrees of freedom. Pearson residuals require degrees of freedom above two;
PIT/quantile residuals and predictive checks remain available with infinite
variance. Predictive plots also support native response families whose
analytic residual distributions are unavailable.
Native grouped-family GAM and joint GJRM diagnostics accept response = NULL
for all responses or a single integer for one response. For mgcv::gfam(),
this integer indexes the family list and selects observations assigned to
that component. Repeated instances of the same family have distinct indices.
For GJRM, it indexes responses in model order.
Selection leaves by_family independent: grouped-family quantile residuals
remain pooled by default, traditional residuals use facets, and explicit
TRUE or FALSE chooses the layout. Appraisal observed-versus-fitted panels
always use component facets. Original component labels and row identities
remain available after selection.
Selected grouped-family residuals contain retained fitting observations only.
The all-component call preserves the usual na.exclude restoration of omitted
rows. With an explicit seed, selected residuals match the corresponding rows
of the all-component calculation when all components support it. Selecting a
supported component can also bypass an unsupported component. Grouped-family
posterior predictive checks accept the same selector and retain joint
coefficient draws for the fitted model.
Factor-valued binomial responses are Bernoulli observations, even when likelihood weights exceed one. Numeric proportions use the fitted trial counts; paired success/failure counts retain their grouped-binomial encoding. Default response simulations and CDFs follow that distinction. Explicit GAM sampling weights can change trial counts or response precision, including Gaussian AR1 precision, without changing fitted coefficient uncertainty. MASS negative-binomial GLM families use their fitted size parameter. The native gaulss likelihood ignores fitting weights, so its default diagnostic references use the fitted inverse standard deviation directly. Explicit sampling precision weights remain available; see the sampling documentation for how these change the response distribution.
Native beta-regression simulation clips draws at epsilon and one minus epsilon. These endpoints therefore have probability mass. Diagnostics include that mass in their CDFs and randomisation and use moments of the same clipped distribution. This is labelled an approximation: the fitting likelihood evaluates the underlying beta density at epsilon-adjusted observations. Distribution functions supplied by callers are preserved.
GEV and sinh-arcsinh checks use stable response means and correct residual centering and signs for both observed and simulated responses. Their deviance magnitudes follow the fitting package's definitions: GEV uses the square root of its saturated log-likelihood contrast; sinh-arcsinh uses zero log density as its reference. If a sinh-arcsinh density exceeds one, that contrast is negative. Deviance checks then give an error rather than replace the residual with zero; response and PIT/quantile checks remain available. These deviance definitions do not produce comparable standardised scores across families. Use PIT/quantile residuals for uniform/standard-normal references.
GEV means and variances require shape below one and one-half, respectively. Signed deviance checks also require a finite mean and shape at least minus one. PIT/quantile checks do not require these moments. When the response mean does not exist, appraisal explains why the observed-versus-fitted panel is unavailable and retains the PIT/quantile panels.
nlme calculations retain covariance between random effects, including nested groups and block designs. They also retain the contrasts and observation order used for fitting, including after subsetting or missing-value removal. Changing global contrast options after fitting does not change the diagnostics.
For response references, conditioning = "conditional" usually holds fitted
random effects and nuisance parameters fixed. "marginal" simulates new
effects from their fitted distributions and averages over them. Setting random
effects to zero is not a substitute for this averaging, especially with
nonlinear response links. sdmTMB has additional field choices described below.
PPCs separately include approximate uncertainty in fitted parameters.
"gam_component" explicitly uses the extracted GAM component. gamm and
gamm4 diagnostics and posterior predictive checks default to the full model
with conditional conditioning. gamm4 response simulations use the same default;
the existing gamm response simulator retains its GAM-component default.
Conditional response references hold fitted effects fixed, while conditional
PPCs include uncertainty in those fitted effects. Specify "marginal" to
simulate new effects instead.
Conditional glmmTMB/lme4 response likelihoods factorize given all random effects, including temporal and spatial effects. Marginal responses may be dependent because they share those effects. An independent effect for each observation need not create dependence between observations. The calculations check covariance implied by the fitted random-effect design, including correlated slopes and covariance cancellation. Gaussian nlme residual correlation can remain after conditioning on random effects; variance weights alone do not introduce correlation.
A conditional check at estimated effects assesses the response distribution at those estimates. It does not provide a calibrated test of random-effect covariance or of the whole fitted model. Marginal joint references assess response variation implied by new simulated effects. A QQ plot checks the distribution of residuals; inspect their ordering or spatial pattern as well to assess dependence. Models are not refitted when calculating reference bands.
Gaussian identity-link AR1 BAM retains joint response simulation, with new
independent series starting at AR.start boundaries. For non-Gaussian or
nonidentity models fitted with discrete = TRUE and nonzero rho, BAM applies
AR1 to working residuals as a generalized estimating equations (GEE)
approximation. This does not specify a unique joint response distribution.
The restriction applies to supported extended.family and GLM families.
See https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/bam.html.
Fitted marginal CDFs, inverse CDFs and PIT/quantile residuals remain useful.
For traditional residuals, the default QQ plot and a requested inverse-CDF
QQ plot use method = "marginal". This approximates the pooled distribution
of individual residuals by numerical sampling, without asserting independence
or supplying dependence bands. Explicit method = "simulate", joint response
simulation and PPCs give an explanatory error. No additional dependence model,
such as a copula, is introduced. An explicitly requested "normal" approximation
is available without independence-based bands; it is never the default here.
residual_correlation() and residual_correlation_plot() provide approximate
checks of correlation between residuals at different lags. For non-Gaussian
BAM, the stored std.rsd residuals differ from the weighted working residuals
used in fitting. Adjusting working residuals for the fitted AR1 correlation
(whitening) or using std.rsd can reveal remaining serial structure. Neither
supplies a generative response model or calibrated p-values. Series boundaries
and gaps from missing observations are retained, and no significance bands
based on independence are drawn. Lags count observation positions, not spatial
distance or irregular elapsed time. Specify series and order the fitting data
to suit the dependence being checked.
With fixed-effect coefficients and covariance parameters held at their maximum likelihood estimates (MLEs):
field_method = "mle-mvn" (default) follows sdmTMB's recommended approach:
draw the fitted fields together from their approximate posterior distribution,
then hold that draw fixed for conditional PITs and response references.
Response errors are independent given those fields. Reference bands use
the same draw as the observed residuals.
"mle-eb" holds empirical-Bayes field estimates fixed. This matches sdmTMB's
residual construction at fitted fields, which its documentation does not
recommend for goodness-of-fit testing. Shrinkage and estimation can distort
the resulting residual distribution.
"mle-mvn-integrated" averages over approximate uncertainty in fitted fields
using sdmTMB's joint response simulations. Residuals are calculated from ranks
in these simulations rather than from one fixed draw of fields. This reuses
the fitting data and can give conservative checks; treat the results as
approximate posterior predictive checks.
conditioning = "marginal" instead simulates new spatial, spatiotemporal
and grouping effects. Simulation at fitting observations also renews other
supported field and time-varying effects; smooths remain fitted. field_method
does not cause another field draw in this mode.
gratia.diagnostics.field_seed (default 1) makes the posterior field draw
reproducible independently of PIT randomisation. All panels use the same draw.
To inspect further draws, change this option and present the results together.
The sdmTMB definitions and recommendations are documented at
https://sdmtmb.github.io/sdmTMB/reference/residuals.sdmTMB.html and
https://sdmtmb.github.io/sdmTMB/articles/residual-checking.html.
PPCs use a separate approximation that draws fixed-effect, nuisance and field parameters together. Marginal PPCs simulate new fields at each parameter draw; smooths retain their posterior draws. Plot captions identify conditioning. Parameter estimation, the Gaussian approximation to the posterior and finite simulation error affect these checks. None of these modes guarantees that goodness-of-fit tests attain their nominal false-positive rate after fitting.
Analytic PIT/quantile QQ plots use uniform/standard-normal reference quantiles.
For ideal independent responses, bands are pointwise intervals for ordered
residuals. For dependent responses, bands come from joint simulations
(n_simulate) when a joint generator exists. Otherwise the bands are omitted
and the plot explains why. Bands condition on the chosen fitted distribution
and fields. They do not provide simultaneous coverage or account for refitting.
When a joint simulator is available but marginal CDFs or moments cannot be
calculated analytically, one reference sample of simulated data sets supplies
means, variances and residual ranks. With R reference draws, PIT is
(number below + U * (ties + 1))/(R + 1), where U is uniform on (0, 1).
The extra rank position is for the observation being checked, which keeps
normal scores finite even outside the simulated range. Observed and simulated
responses use the same reference sample, centering and residual definitions.
These ranks need not equal the empirical CDF at an observation.
options(gratia.diagnostics.marginal_draws = 249L) sets the reference sample
size (minimum 19). Increase it to assess sensitivity to Monte Carlo error.
gratia.diagnostics.marginal_seed (default 1) makes this sample reproducible
independently of residual randomisation. A finite sample limits tail resolution
and moment accuracy. Moment estimates require finite population moments:
glmmTMB Student-t response residuals require df > 1, and Pearson residuals
require df > 2. An undefined moment is not replaced by a finite sample estimate.
PIT/quantile checks and joint draws remain available, but an undefined mean
cannot be shown as a fitted expectation. Bands for residuals calculated from
simulation ranks use joint draws and the same rank transformation, even if
the underlying responses are independent. Marginal deviance residuals remain
unavailable where the integrated likelihood has no defined deviance; use
response, Pearson or quantile residuals instead.
dharma_residuals() and type = "dharma" implement simulation-based PIT
residuals using gratia's existing generators, without requiring DHARMa or
mgcViz. Responses are ranked against n_dharma simulated datasets (default
250), with randomisation within ties and exact zero and one endpoints.
This calculation differs from the existing simulation-rank formula above:
it uses the empirical fractions below and below or equal to the observation,
without an extra rank position. Existing PIT and quantile residuals retain
their current definitions.
The calculation needs comparable scalar response draws, but no CDF or finite response moments. Existing model adapters retain their conditioning defaults. Marginal-only generators provide marginal distribution checks. Censored and multivariate observations are unsupported. Independent responses use uniform QQ references with approximate pointwise bands because the simulation count is finite; dependent responses omit independence-based bands.
Inverse CDFs with direct lower/upper and log-probability arguments preserve extreme interior quantiles. Older functions that accept only lower-tail probabilities cannot always represent an extreme upper-tail probability. If conversion rounds it to an endpoint and produces a false infinite quantile, an explanatory error is raised. This limits extreme upper quantiles of the compound-Poisson Tweedie distribution. The Gamma boundary and inverse-Gaussian solver accept log probabilities directly. True probability endpoints remain valid.
BAM/PQL working correlations need a scientifically specified joint response
model before joint simulation or PPC can be added. Additional GJRM and other
fitting-package families should supply their parameters to the shared response
distributions. Censored/survival PPCs need a way to reapply censoring to each
simulated response. Nominal multivariate PITs need a documented category
ordering or a different multivariate diagnostic. Unrecognised random-effect
structures remain unsupported. Diagnostics do not repair na.pass fits where
missing responses cannot be aligned with predictions and residuals; ordinary
na.omit/na.exclude fits are covered. MCMC, model refitting and calibrated
dependence tests would require additional sampling or refitting methods.
Like mgcViz, these diagnostics use residuals with known reference distributions where available and aggregate large data sets before plotting. All observations and QQ endpoints contribute. Kernel density estimates and histograms remain available as separate views. See https://mfasiolo.github.io/mgcViz/reference/qq.gamViz.html. mgcViz approximates QQ plots on a discrete grid; gratia aggregates plot points but preserves exact pooled reference quantiles. mgcViz also plots differences between empirical and model-implied conditional densities. Adding such plots would require comparable smoothing bandwidths and a validated conditional reference. The existing density and histogram views retain information about scale misspecification rather than rescaling every residual to unit variance. See https://mfasiolo.github.io/mgcViz/reference/l_densCheck.html.
Uniform references average ordered residuals as draws are generated, without
storing all draws. Simulated QQ uses exact pooled quantiles computed as by
stats::quantile(type = 7) and pointwise intervals for each residual rank.
Above options(gratia.diagnostics.max_cells = 1e7), sorted draws are written
to temporary files and merged exactly. This limits simulation memory use at
the cost of disk I/O. One response vector and the reference output must still
fit in memory. Scalable PPCs summarise every draw on the same grid; discrete
responses with more than 512 distinct values use labelled probabilities for
512 bins. posterior_samples() returns the raw response draws. Coefficient
and random-effect draws still need memory proportional to the number of
parameters times the number of draws.
The internal fix_family_rd(), fix_family_cdf() and fix_family_qf()
functions still add $rd, $cdf and $qf to mgcv-compatible families while
preserving functions supplied by callers. The fitted-distribution code adapts
their arguments locally. Families can supply a gratia_diagnostics function
for response moments, probability bounds and other distribution information;
see family_diagnostics for the interface. Other fitting packages can use the
same standard
response distributions, or combine them by family index, truncate them or add
point masses without changing the plotting calculations.
appraise(), quantile_residuals(), qq_plot(),
scalable_qq_plot(), posterior_predictive_plot(), gamm4_support
Estimates pairwise differences (comparisons) between factor smooth
interactions (smooths with a factor by argument) for pairs of groups
defined by the factor. The group means can be optionally included in the
difference. First and second derivatives of these differences, including
partial derivatives across smooth surfaces, can also be estimated.
difference_smooths(model, ...) ## S3 method for class 'gam' difference_smooths( model, select = NULL, smooth = deprecated(), n = 100, n_2d = 50, ci_level = 0.95, data = NULL, group_means = FALSE, partial_match = TRUE, unconditional = FALSE, frequentist = FALSE, envir = NULL, ..., interval = c("confidence", "simultaneous"), n_sim = 10000, n_cores = 1, seed = NULL, variables = NULL, n_3d = 16, n_4d = 4, simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list(), order = 0L, focal = NULL, type = c("central", "forward", "backward"), eps = NULL, wrt = c("smooth", "covariate") ) ## S3 method for class 'scam' difference_smooths(model, ..., unconditional = FALSE)difference_smooths(model, ...) ## S3 method for class 'gam' difference_smooths( model, select = NULL, smooth = deprecated(), n = 100, n_2d = 50, ci_level = 0.95, data = NULL, group_means = FALSE, partial_match = TRUE, unconditional = FALSE, frequentist = FALSE, envir = NULL, ..., interval = c("confidence", "simultaneous"), n_sim = 10000, n_cores = 1, seed = NULL, variables = NULL, n_3d = 16, n_4d = 4, simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list(), order = 0L, focal = NULL, type = c("central", "forward", "backward"), eps = NULL, wrt = c("smooth", "covariate") ) ## S3 method for class 'scam' difference_smooths(model, ..., unconditional = FALSE)
model |
A fitted model. |
... |
arguments passed to other methods. Not currently used. |
select |
character, logical, or numeric; which smooths to compare. If
For character |
smooth |
|
n |
numeric; the number of points at which to evaluate the difference between pairs of smooths. |
n_2d |
numeric; the number of points along each of the first two axes
of a smooth surface, including surface panels of higher-dimensional smooths.
The default is 50 in plotting and plot-preparation functions. If |
ci_level |
numeric between 0 and 1; the coverage of credible interval. |
data |
data frame of locations at which to evaluate the difference between smooths. |
group_means |
logical; should the group means be included in the
difference? Must be |
partial_match |
logical; should |
unconditional |
logical; account for smoothness selection in the model? |
frequentist |
logical; use the frequentist covariance matrix? |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
interval |
character; |
n_sim |
positive integer; number of coefficient draws used for simultaneous intervals. Ignored for pointwise intervals. |
n_cores |
positive integer; number of cores used by |
seed |
integer or |
variables |
Character vector giving every covariate of the selected
smooths exactly once, in plotting order: x, y, then the conditioning
covariate for 3D smooths, or facet rows and columns for 4D smooths.
When supplied, selected smooths must use the same covariates. Use fitted coordinate names,
such as |
n_3d, n_4d
|
numeric; the number of conditioning values for smooths of
three or four covariates. The defaults are 16 and 4, respectively. If
|
simultaneous_method |
character; calibration for simultaneous bands.
The default, |
simultaneous_domain |
numeric pair of increasing finite endpoints, or
a named list of such pairs keyed by spline coordinate. For tube bands,
|
tube_control |
named list controlling numerical tube calibration:
|
order |
numeric; |
focal |
character; one differentiation coordinate shared by all
compared smooths. Inferred for univariate smooths; required for
multivariate smooths when |
type |
character; finite-difference scheme for derivatives. One of
|
eps |
a positive finite number giving the absolute finite-difference
step, or |
wrt |
differentiation coordinate: |
With the default simulation calibration, simultaneous intervals cover smooth differences at
the evaluated covariate combinations for each pair of factor levels, with
approximate posterior probability ci_level when using the Bayesian
covariance. They do not provide joint coverage across all pairs, outside
the evaluation set, or between its points. With data = NULL, the evaluation
set is generated using n, n_2d, n_3d, and n_4d. Differences and interval
limits are on the linear predictor scale, including group means when requested.
For supported univariate cubic splines, simultaneous_method = "tube"
instead covers a continuous interval, including between returned points;
see simultaneous_bands. Coverage remains separate for each pair.
variables determines the order used to generate and display the evaluation
grid. The first two covariates are the x and y axes. The third covariate
defines facets for three-dimensional smooths, or facet rows for
four-dimensional smooths; the fourth defines facet columns. Use data to
choose particular conditioning values. The resolved order is saved with the
estimates for use by draw().
The intervals use the joint coefficient covariance selected by
unconditional and frequentist, retaining covariance between the two
smooths. The covariance must be positive semidefinite. With
frequentist = TRUE, simulation instead uses the frequentist covariance
of the coefficient estimators. n_sim, n_cores, and seed are ignored for
pointwise intervals. An explicit seed scopes the entire call: each pair uses
a new batch of coefficient draws, and the caller's random number state is
restored on exit. With seed = NULL, the current random number state is
used and advanced.
With order > 0, the estimate is the difference between the derivatives
of the selected smooths, on the linear predictor scale. Equivalently, it is
the derivative of their difference. The estimate and its uncertainty are
computed from the difference of the derivative matrices, retaining covariance
between the smooths. Group means are excluded, and tube intervals are
unavailable for derivatives; use simulation for simultaneous intervals.
For a multivariate smooth, focal identifies the coordinate to differentiate.
All other independent coordinates are fixed at their value in each evaluation
row. They can vary between rows, so data may describe a full surface or
several slices. order = 2 differentiates twice with respect to focal;
mixed partial derivatives are not supported. Generated grids adjust the
focal range for the finite-difference scheme; supplied evaluation locations
are preserved.
With wrt = "covariate", model expressions are reevaluated after changing
the raw focal covariate. Generated raw grids use smooth_data() and require
each axis to depend on one distinct original covariate. Supply raw data
for other transformations. With wrt = "smooth", only the named smooth
coordinate is changed. Derivative controls are ignored when order = 0.
Raw-coordinate comparisons match the same original covariates, excluding
the comparison factor. Evaluated smooth coordinates may differ between
factor levels when a transformation involves that factor. The finite-difference
step must fit within the fitted focal range for generated grids, including
grids with only one focal value.
A tibble of class "difference_smooth". Columns .smooth, .by,
.level_1, and .level_2 identify each comparison; .diff contains the
estimate for level 1 minus level 2, with .se, .lower_ci, .upper_ci,
and evaluation covariates. For order > 0, .diff contains the derivative
difference and .focal names its coordinate. The derivative_info
attribute records order, focal, wrt, type, and the resolved step
eps. The plot_variables attribute records the plotting axes.
With mirai and carrier installed, configure workers with
mirai::daemons() to distribute calculations across selected smooths.
difference_smooths() distributes factor-level comparisons instead.
Without configured workers, or with only one calculation, evaluation is
serial. These functions leave the caller's worker pool running.
Model selection, evaluation of model expressions and random draws are
prepared in the caller. Workers receive the coordinates and coefficient
columns needed for their calculation. Custom prediction methods are evaluated
in the caller, including custom tensor margins and factor-smooth bases;
workers receive their prediction matrices. Simultaneous intervals use successive
draws in selection order, so set.seed() gives the same results with or
without workers, independently of their number or completion order.
derivatives() uses set.seed(); the other functions also accept seed,
which restores the caller's random number state on exit.
smooth_samples() draws coefficients jointly once, then reuses those draws
for every smooth, preserving dependence and chain identities. Sampling
finishes before smooth calculations start, so MH chains and smooth workers
are not nested. Sampling thread controls keep their existing meanings.
Workers use their configured BLAS thread settings; when using a threaded
BLAS, limit its threads before starting daemons to avoid competing threads.
Parallel work is most useful for expensive bases or interval calculations. Small grids can be slower because of transfer and scheduling costs. Large grids and many draws also require memory for worker inputs and returned results, in addition to the final output.
derivatives(), partial_derivatives()
load_mgcv() # Simulate group-specific curves with Gaussian noise and fit factor-by smooths df <- data_sim("eg4", n = 300, seed = 42) m <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = df, method = "REML") # Compare the centred smooth shapes for each pair of factor levels sm_dif <- difference_smooths(m, select = "s(x2)") sm_dif draw(sm_dif) # Compare rates of change instead of smooth values, using the same fit slope_dif <- difference_smooths(m, select = "s(x2)", order = 1) slope_difload_mgcv() # Simulate group-specific curves with Gaussian noise and fit factor-by smooths df <- data_sim("eg4", n = 300, seed = 42) m <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = df, method = "REML") # Compare the centred smooth shapes for each pair of factor levels sm_dif <- difference_smooths(m, select = "s(x2)") sm_dif draw(sm_dif) # Compare rates of change instead of smooth values, using the same fit slope_dif <- difference_smooths(m, select = "s(x2)", order = 1) slope_dif
## S3 method for class 'gamm4' dispersion(model, ...) ## S3 method for class 'scam' dispersion(model, ...) dispersion(model, ...) ## S3 method for class 'gam' dispersion(model, ...) ## S3 method for class 'glm' dispersion(model, ...)## S3 method for class 'gamm4' dispersion(model, ...) ## S3 method for class 'scam' dispersion(model, ...) dispersion(model, ...) ## S3 method for class 'gam' dispersion(model, ...) ## S3 method for class 'glm' dispersion(model, ...)
model |
a fitted model. |
... |
arguments passed to other methods. |
ggplot2
Generic plotting via ggplot2
draw(object, ..., label_control = NULL)draw(object, ..., label_control = NULL)
object |
and R object to plot. |
... |
arguments passed to other methods. |
label_control |
Optional layout settings created by
|
Generic function for plotting of R objects that uses the ggplot2 package.
A ggplot2::ggplot() object.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Gavin L. Simpson
Configure labels on axes, legends and colour bars across draw() and
assemble() methods. Omitted settings retain the existing appearance.
draw_label_control(axes = list(), legend = list(), colourbar = list())draw_label_control(axes = list(), legend = list(), colourbar = list())
axes |
Named list with optional |
legend |
Named list with optional |
colourbar |
Named list with optional |
Every setting defaults to NULL, retaining the method's existing behaviour.
Pass the result as label_control to draw() or assemble(). The same
configuration can be reused across plot types; absent guides are ignored.
Mathematical expressions and missing labels are preserved. Wrapping changes
displayed text after scale labelling, without changing factor levels,
breaks, transformations or palettes. Numeric formatting remains controlled
by the scale's labels argument.
Explicit axis settings override the existing angle and n_dodge plotting
arguments on discrete axes. Hidden guides stay hidden. Native guide types
and unrelated settings are retained; later ggplot2 scale and guide additions
follow their usual precedence. Settings apply to panels before patchwork
collects their guides, including plots returned with wrap = FALSE.
Projected coordinate labels in 3D plots retain their renderer's settings;
their ordinary legends and colour bars can use this control.
A draw_label_control object.
draw(), assemble(), gratia_theme_get()
# Wrap categorical tick labels and stagger them across two rows. layout <- draw_label_control(axes = list(wrap = 12, n_dodge = 2)) # Reuse one configuration for legend text and colour-bar layout. layout <- draw_label_control( axes = list(wrap = 12), legend = list(wrap = 20, title_wrap = 20, ncol = 2), colourbar = list(title_wrap = 20, height = grid::unit(35, "mm")) ) # Draw a model with the requested layout. load_mgcv() dat <- data_sim("eg4", n = 100, seed = 42) model <- gam(y ~ fac + s(x2, by = fac, k = 5), data = dat, method = "REML") draw(model, label_control = layout)# Wrap categorical tick labels and stagger them across two rows. layout <- draw_label_control(axes = list(wrap = 12, n_dodge = 2)) # Reuse one configuration for legend text and colour-bar layout. layout <- draw_label_control( axes = list(wrap = 12), legend = list(wrap = 20, title_wrap = 20, ncol = 2), colourbar = list(title_wrap = 20, height = grid::unit(35, "mm")) ) # Draw a model with the requested layout. load_mgcv() dat <- data_sim("eg4", n = 100, seed = 42) model <- gam(y ~ fac + s(x2, by = fac, k = 5), data = dat, method = "REML") draw(model, label_control = layout)
Plot saved ALE estimates and intervals, without recomputing predictions.
## S3 method for class 'ale' draw( object, ci = TRUE, ref_line = TRUE, alpha = 0.2, xlab = NULL, ylab = NULL, ... )## S3 method for class 'ale' draw( object, ci = TRUE, ref_line = TRUE, alpha = 0.2, xlab = NULL, ylab = NULL, ... )
object |
a tibble of class |
ci |
logical; show the saved interval ribbon? |
ref_line |
logical; draw a horizontal reference line at zero? |
alpha |
Deprecated; use |
xlab, ylab
|
optional axis labels. Defaults identify the focal covariate
and selected parameter. The computation scale appears in the caption.
Titles and subtitles are omitted. Use |
... |
reserved for future use. |
A ggplot2::ggplot() object.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
load_mgcv() df <- data_sim("eg1", n = 100, seed = 2) m <- gam(y ~ s(x2), data = df, method = "REML") ale(m, "x2") |> draw()load_mgcv() df <- data_sim("eg1", n = 100, seed = 2) m <- gam(y ~ s(x2), data = df, method = "REML") ale(m, "x2") |> draw()
Plots basis functions using ggplot2
## S3 method for class 'basis' draw( object, legend = FALSE, labeller = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ncol = NULL, nrow = NULL, angle = NULL, guides = "keep", contour = TRUE, n_contour = 10, contour_col = "black", ..., variables = NULL )## S3 method for class 'basis' draw( object, legend = FALSE, labeller = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ncol = NULL, nrow = NULL, angle = NULL, guides = "keep", contour = TRUE, n_contour = 10, contour_col = "black", ..., variables = NULL )
object |
an object, the result of a call to |
legend |
logical; should a legend by drawn to indicate basis functions? |
labeller |
a labeller function with which to label facets. The default
is to use |
ylab |
character or expression; the label for the y axis. If not
supplied, a suitable label will be generated from |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
guides |
character; one of |
contour |
logical; should contours be draw on the plot using
|
n_contour |
numeric; the number of contour bins. Will result in
|
contour_col |
Deprecated; use |
... |
arguments passed to other methods. Not used by this method. |
variables |
Character vector giving every covariate of the selected
smooths exactly once, in plotting order: x, y, then the conditioning
covariate for 3D smooths, or facet rows and columns for 4D smooths.
When supplied, selected smooths must use the same covariates. Use fitted coordinate names,
such as |
For smooths of three or four covariates, each basis function has its own
plot. The first two covariates define the surface axes. Three-covariate
smooths have wrapped facets for the third covariate; four-covariate smooths
have the third covariate in rows and the fourth in columns. ncol and nrow
control the outer arrangement of plots. Fill scales share a range within
each smooth. Use variables in basis() to choose the axes before grid
generation, or here to rearrange existing evaluations without resampling.
Surface plots include contour lines by default, matching draw.gam().
Use contour = FALSE to draw surfaces without contour lines.
Factor-by bases from smooth specifications are drawn once for the whole
factor-by set, using evaluations from all available levels. For fitted
models, basis(model) returns coefficient-weighted contributions, which
remain separate for each level. Use basis(model, unweighted = TRUE) to
draw the shared basis once. Subsetting the basis before drawing restricts
the plot to the retained evaluations and basis functions.
A patchwork object.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Gavin L. Simpson
load_mgcv() # Simulate an additive Gaussian response and fit a GAM df <- data_sim("eg1", n = 200, seed = 42) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # Plot the coefficient-weighted basis functions for one smooth bf <- basis(m, select = "s(x2)") draw(bf)load_mgcv() # Simulate an additive Gaussian response and fit a GAM df <- data_sim("eg1", n = 200, seed = 42) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # Plot the coefficient-weighted basis functions for one smooth bf <- basis(m, select = "s(x2)") draw(bf)
Plot comparisons of smooths
## S3 method for class 'compare_smooths' draw( object, ncol = NULL, nrow = NULL, guides = "collect", select = NULL, partial_match = FALSE, show = c("models", "difference"), pair = NULL, ci_level = 0.95, surface = c("raster", "tile"), contour = TRUE, n_contour = NULL, continuous_fill = NULL, ... )## S3 method for class 'compare_smooths' draw( object, ncol = NULL, nrow = NULL, guides = "collect", select = NULL, partial_match = FALSE, show = c("models", "difference"), pair = NULL, ci_level = 0.95, surface = c("raster", "tile"), contour = TRUE, n_contour = NULL, continuous_fill = NULL, ... )
object |
of class |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
guides |
character; guide handling for the combined plot, passed to
|
select, partial_match
|
select smooths from the comparison, using the
conventions of |
show |
character; |
pair |
two model names or integer indices in input order. In difference
mode, subtract the second model from the first. With exactly two models,
the default uses their input order; with more models, supply |
ci_level |
numeric; one finite value strictly between 0 and 1, giving
the coverage of the pointwise normal intervals for one-variable smooths.
The default is |
surface |
character; |
contour |
logical; add contour lines? These require two numeric axes and at least one grid cell with four finite corner values that are not all equal. |
n_contour |
numeric; the number of contour bins. Will result in
|
continuous_fill |
a suitable fill scale to be used when plotting continuous variables. |
... |
arguments passed to |
Difference plots match both coordinates and any retained conditioning
covariates. Locations missing from either model, and missing estimates, remain
missing. Multiple conditioning values are drawn in separate panels.
No interval is calculated for the difference: estimates from models fitted
to the same observations can be correlated, and their separate covariance
matrices do not supply the covariance between models. See compare_smooths()
for the scale and centring of the compared smooth contributions.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Display conditional differences as curves with pointwise or simultaneous
intervals and a zero reference line, or as surfaces over two grouped numeric
covariates. Each comparison is shown in a separate facet. Surfaces map the
difference to fill and, in 3D, height, with a fill range symmetric around zero.
Additional conditions supply facets for surfaces, or colour and facets for
curves, as in draw.conditional_values().
## S3 method for class 'conditional_differences' draw( object, facet_scales = "fixed", discrete_colour = NULL, discrete_fill = NULL, xlab = NULL, ylab = NULL, ..., surface = c("raster", "tile", "3d"), surface_3d = list(), continuous_fill = NULL, contour = TRUE, n_contour = NULL, ci_3d = FALSE, zlab = NULL )## S3 method for class 'conditional_differences' draw( object, facet_scales = "fixed", discrete_colour = NULL, discrete_fill = NULL, xlab = NULL, ylab = NULL, ..., surface = c("raster", "tile", "3d"), surface_3d = list(), continuous_fill = NULL, contour = TRUE, n_contour = NULL, ci_3d = FALSE, zlab = NULL )
object |
an object returned by |
facet_scales |
character; should facets have the same axis scales
across facets? See |
discrete_colour |
a suitable colour scale to be used when plotting discrete variables. |
discrete_fill |
a suitable fill scale to be used when plotting discrete variables. |
xlab |
character; label for the x axis of the plot. |
ylab |
character; label for the prediction axis of a curve, or the second covariate axis of a surface. |
... |
arguments passed to |
surface |
character; |
surface_3d |
named list of view options passed to |
continuous_fill |
a suitable fill scale to be used when plotting continuous variables. |
contour |
logical; draw contour lines on surfaces? Defaults to |
n_contour |
numeric; the number of contour bins. Will result in
|
ci_3d |
logical; add the returned lower and upper interval surfaces
when |
zlab |
character; label for the surface fill legend and 3D height axis. Defaults to the prediction label, or the difference and its scale for conditional differences. |
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
load_mgcv() df <- data_sim("eg4", seed = 2) m <- gam(y ~ fac + s(x2, by = fac), data = df, method = "REML") draw(conditional_differences(m, by = "fac", condition = "x2"))load_mgcv() df <- data_sim("eg4", seed = 2) m <- gam(y ~ fac + s(x2, by = fac), data = df, method = "REML") draw(conditional_differences(m, by = "fac", condition = "x2"))
Draw conditional response moments
## S3 method for class 'conditional_moments' draw( object, facet_scales = "fixed", discrete_colour = NULL, discrete_fill = NULL, xlab = NULL, ylab = NULL, ... )## S3 method for class 'conditional_moments' draw( object, facet_scales = "fixed", discrete_colour = NULL, discrete_fill = NULL, xlab = NULL, ylab = NULL, ... )
object |
A tibble returned by |
facet_scales |
character; should facets have the same axis scales
across facets? See |
discrete_colour |
a suitable colour scale to be used when plotting discrete variables. |
discrete_fill |
a suitable fill scale to be used when plotting discrete variables. |
xlab |
character; label for the x axis of the plot. |
ylab |
Character; label for the response moment axis. |
... |
Additional arguments passed to |
A patchwork containing one plot per moment and response/category.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Curves show predictions and intervals. Grouped numeric conditions show a
surface, with predictions mapped to fill and, for surface = "3d", height.
Remaining conditions create separate facets. Flat surfaces show estimates;
ci_3d = TRUE adds the returned lower and upper interval surfaces in 3D.
## S3 method for class 'conditional_values' draw( object, facet_scales = "fixed", discrete_colour = NULL, discrete_fill = NULL, xlab = NULL, ylab = NULL, ..., surface = c("raster", "tile", "3d"), surface_3d = list(), continuous_fill = NULL, contour = TRUE, n_contour = NULL, ci_3d = FALSE, zlab = NULL )## S3 method for class 'conditional_values' draw( object, facet_scales = "fixed", discrete_colour = NULL, discrete_fill = NULL, xlab = NULL, ylab = NULL, ..., surface = c("raster", "tile", "3d"), surface_3d = list(), continuous_fill = NULL, contour = TRUE, n_contour = NULL, ci_3d = FALSE, zlab = NULL )
object |
an object of class |
facet_scales |
character; should facets have the same axis scales
across facets? See |
discrete_colour |
a suitable colour scale to be used when plotting discrete variables. |
discrete_fill |
a suitable fill scale to be used when plotting discrete variables. |
xlab |
character; label for the x axis of the plot. |
ylab |
character; label for the prediction axis of a curve, or the second covariate axis of a surface. |
... |
additional arguments; currently unused. |
surface |
character; |
surface_3d |
named list of view options passed to |
continuous_fill |
a suitable fill scale to be used when plotting continuous variables. |
contour |
logical; draw contour lines on surfaces? Defaults to |
n_contour |
numeric; the number of contour bins. Will result in
|
ci_3d |
logical; add the returned lower and upper interval surfaces
when |
zlab |
character; label for the surface fill legend and 3D height axis. Defaults to the prediction label, or the difference and its scale for conditional differences. |
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Plot derivatives of smooths
## S3 method for class 'derivatives' draw( object, select = NULL, scales = c("free", "fixed"), add_change = FALSE, change_type = c("change", "sizer"), alpha = 0.2, change_col = "black", decrease_col = "#56B4E9", increase_col = "#E69F00", lwd_change = 1.5, ncol = NULL, nrow = NULL, guides = "keep", angle = NULL, differentiate_factor_smooths = TRUE, ... ) ## S3 method for class 'partial_derivatives' draw( object, select = NULL, scales = c("free", "fixed"), alpha = 0.2, ncol = NULL, nrow = NULL, guides = "keep", angle = NULL, ... )## S3 method for class 'derivatives' draw( object, select = NULL, scales = c("free", "fixed"), add_change = FALSE, change_type = c("change", "sizer"), alpha = 0.2, change_col = "black", decrease_col = "#56B4E9", increase_col = "#E69F00", lwd_change = 1.5, ncol = NULL, nrow = NULL, guides = "keep", angle = NULL, differentiate_factor_smooths = TRUE, ... ) ## S3 method for class 'partial_derivatives' draw( object, select = NULL, scales = c("free", "fixed"), alpha = 0.2, ncol = NULL, nrow = NULL, guides = "keep", angle = NULL, ... )
object |
a fitted GAM, the result of a call to |
select |
character, logical, or numeric; which smooths to plot. If
|
scales |
character; should all univariate smooths be plotted with the
same y-axis scale? If Currently does not affect the y-axis scale of plots of the parametric terms. |
add_change |
logical; should the periods of significant change be highlighted on the plot? |
change_type |
character; the type of change to indicate. If |
alpha |
Deprecated; use |
change_col, decrease_col, increase_col
|
Deprecated; use |
lwd_change |
Deprecated; use |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
guides |
character; one of |
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
differentiate_factor_smooths |
logical; should colour be used to
differentiate the levels of the factors involved in random factor smooths
( |
... |
additional arguments passed to |
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
load_mgcv() # Simulate an additive Gaussian response and fit a GAM dat <- data_sim("eg1", n = 200, scale = 1, seed = 42) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # Estimate and plot the rate of change of one smooth df <- derivatives(mod, select = "s(x2)", type = "central") draw(df)load_mgcv() # Simulate an additive Gaussian response and fit a GAM dat <- data_sim("eg1", n = 200, scale = 1, seed = 42) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # Estimate and plot the rate of change of one smooth df <- derivatives(mod, select = "s(x2)", type = "central") draw(df)
Plot differences of smooths
## S3 method for class 'difference_smooth' draw( object, select = NULL, rug = FALSE, ref_line = FALSE, contour = FALSE, contour_col = "black", n_contour = NULL, ci_alpha = 0.2, ci_col = "black", smooth_col = "black", line_col = "red", scales = c("free", "fixed"), ncol = NULL, nrow = NULL, guides = "keep", xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, angle = NULL, ..., variables = NULL )## S3 method for class 'difference_smooth' draw( object, select = NULL, rug = FALSE, ref_line = FALSE, contour = FALSE, contour_col = "black", n_contour = NULL, ci_alpha = 0.2, ci_col = "black", smooth_col = "black", line_col = "red", scales = c("free", "fixed"), ncol = NULL, nrow = NULL, guides = "keep", xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, angle = NULL, ..., variables = NULL )
object |
a fitted GAM, the result of a call to |
select |
character, logical, or numeric; which smooths to plot. If
|
rug |
logical; |
ref_line |
logical; |
contour |
logical; should contour lines be added to smooth surfaces? |
contour_col |
Deprecated; use |
n_contour |
numeric; the number of contour bins. Will result in
|
ci_alpha |
Deprecated; use |
ci_col |
Deprecated; use |
smooth_col |
Deprecated; use |
line_col |
Deprecated; use |
scales |
character; should all univariate smooths be plotted with the
same y-axis scale? If Currently does not affect the y-axis scale of plots of the parametric terms. |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
guides |
character; one of |
xlab, ylab, title, subtitle, caption
|
character; labels with which to annotate plots |
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
... |
additional arguments passed to |
variables |
character vector; every covariate of the selected smooth,
in plotting order. The first two are the x and y axes; the third defines
facets for three covariates, or facet rows for four covariates; the fourth
defines facet columns. |
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
load_mgcv() # simulate some data; a factor smooth example df <- data_sim("eg4", seed = 42) # fit GAM m <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = df, method = "REML") # calculate the differences between pairs of smooths the f_j(x2) term diffs <- difference_smooths(m, select = "s(x2)") draw(diffs)load_mgcv() # simulate some data; a factor smooth example df <- data_sim("eg4", seed = 42) # fit GAM m <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = df, method = "REML") # calculate the differences between pairs of smooths the f_j(x2) term diffs <- difference_smooths(m, select = "s(x2)") draw(diffs)
Plots estimated univariate and bivariate smooths using ggplot2.
## S3 method for class 'evaluated_parametric_term' draw( object, ci_level = 0.95, constant = NULL, fun = NULL, xlab, ylab, title = NULL, subtitle = NULL, caption = NULL, rug = TRUE, position = "identity", response_range = NULL, ... )## S3 method for class 'evaluated_parametric_term' draw( object, ci_level = 0.95, constant = NULL, fun = NULL, xlab, ylab, title = NULL, subtitle = NULL, caption = NULL, rug = TRUE, position = "identity", response_range = NULL, ... )
object |
an object, the result of a call to
|
ci_level |
numeric between 0 and 1; the coverage of credible interval. |
constant |
numeric; a constant to add to the estimated values of the
smooth. |
fun |
function; a function that will be applied to the estimated values
and confidence interval before plotting. Can be a function or the name of a
function. Function |
xlab |
character or expression; the label for the x axis. If not
supplied, a suitable label will be generated from |
ylab |
character or expression; the label for the y axis. If not
supplied, a suitable label will be generated from |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
rug |
For |
position |
Position adjustment, either as a string, or the result of a call to a position adjustment function. |
response_range |
numeric; a vector of two values giving the range of
response data for the guide. Used to fix plots to a common scale/range.
Ignored if |
... |
arguments passed to other methods. |
A ggplot2::ggplot() object.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Gavin L. Simpson
Plots smooth and parametric contributions from a fitted GAM model using
ggplot2::ggplot().
For models fitted by mgcv::gamm(), draw() and assemble() use the
fitted gam component.
## S3 method for class 'gam' draw( object, data = NULL, select = NULL, parametric = NULL, terms = NULL, residuals = FALSE, scales = c("free", "fixed"), ci_level = 0.95, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, unconditional = FALSE, overall_uncertainty = TRUE, constant = NULL, fun = NULL, dist = 0.1, rug = TRUE, distinct_rug = TRUE, contour = TRUE, grouped_by = deprecated(), ci_alpha = 0.2, ci_col = "black", smooth_col = "black", resid_col = "steelblue3", contour_col = "black", n_contour = NULL, partial_match = FALSE, discrete_colour = NULL, discrete_fill = NULL, continuous_colour = NULL, continuous_fill = NULL, position = "identity", angle = NULL, ncol = NULL, nrow = NULL, guides = "keep", widths = NULL, heights = NULL, crs = NULL, default_crs = NULL, lims_method = "geometry_bbox", wrap = TRUE, caption = TRUE, envir = NULL, surface = c("raster", "tile", "3d"), surface_3d = list(), ci_3d = FALSE, ci_3d_alpha = 0.15, ci_3d_col = "grey60", back_transform = FALSE, re_levels = NULL, mrf_plot = c("effects", "qq"), interval = c("confidence", "simultaneous"), n_sim = 10000, n_cores = 1, seed = NULL, interval_method = c("auto", "gaussian", "bootstrap", "shape"), frequentist = FALSE, shape_source = c("gaussian", "bootstrap"), ..., variables = NULL, simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list(), cyclic = c("cartesian", "polar"), polar_args = list(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz"), time_varying_style = c("ribbon", "pointrange") ) ## S3 method for class 'gamm' draw(object, ...) ## S3 method for class 'scam' draw(object, ..., overall_uncertainty = FALSE, centre = c("model", "plot")) ## S3 method for class 'scasm' draw( object, ..., overall_uncertainty = FALSE, interval_method = c("auto", "gaussian", "bootstrap", "shape") )## S3 method for class 'gam' draw( object, data = NULL, select = NULL, parametric = NULL, terms = NULL, residuals = FALSE, scales = c("free", "fixed"), ci_level = 0.95, n = 100, n_2d = 50, n_3d = 16, n_4d = 4, unconditional = FALSE, overall_uncertainty = TRUE, constant = NULL, fun = NULL, dist = 0.1, rug = TRUE, distinct_rug = TRUE, contour = TRUE, grouped_by = deprecated(), ci_alpha = 0.2, ci_col = "black", smooth_col = "black", resid_col = "steelblue3", contour_col = "black", n_contour = NULL, partial_match = FALSE, discrete_colour = NULL, discrete_fill = NULL, continuous_colour = NULL, continuous_fill = NULL, position = "identity", angle = NULL, ncol = NULL, nrow = NULL, guides = "keep", widths = NULL, heights = NULL, crs = NULL, default_crs = NULL, lims_method = "geometry_bbox", wrap = TRUE, caption = TRUE, envir = NULL, surface = c("raster", "tile", "3d"), surface_3d = list(), ci_3d = FALSE, ci_3d_alpha = 0.15, ci_3d_col = "grey60", back_transform = FALSE, re_levels = NULL, mrf_plot = c("effects", "qq"), interval = c("confidence", "simultaneous"), n_sim = 10000, n_cores = 1, seed = NULL, interval_method = c("auto", "gaussian", "bootstrap", "shape"), frequentist = FALSE, shape_source = c("gaussian", "bootstrap"), ..., variables = NULL, simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list(), cyclic = c("cartesian", "polar"), polar_args = list(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz"), time_varying_style = c("ribbon", "pointrange") ) ## S3 method for class 'gamm' draw(object, ...) ## S3 method for class 'scam' draw(object, ..., overall_uncertainty = FALSE, centre = c("model", "plot")) ## S3 method for class 'scasm' draw( object, ..., overall_uncertainty = FALSE, interval_method = c("auto", "gaussian", "bootstrap", "shape") )
object |
a fitted GAM, the result of a call to |
data |
an optional data frame that is used to supply the data at which the smooths will be evaluated and plotted. This is usually not needed, but is an option if you need fine control over exactly what data are used for plotting. |
select |
character, logical, or numeric; which smooths to plot. If
|
parametric |
logical or |
terms |
character; which model parametric terms should be drawn? The
Default of |
residuals |
logical; should partial residuals for a smooth be drawn? Ignored for anything but a simple univariate smooth. If the model does not provide working residuals and working weights, warns once and draws the smooths without partial residuals. |
scales |
character; should all univariate smooths be plotted with the
same y-axis scale? If Currently does not affect the y-axis scale of plots of the parametric terms. |
ci_level |
numeric between 0 and 1; the coverage of credible interval. |
n |
numeric; the number of points over the range of the covariate at which to evaluate a univariate smooth. |
n_2d |
numeric; the number of points along each of the first two axes
of a smooth surface, including surface panels of higher-dimensional smooths.
The default is 50 in plotting and plot-preparation functions. If |
n_3d |
numeric; the number of new observations to generate for the third
dimension of a 3D smooth. Factor conditioning dimensions retain at most
this many levels, taking the first levels in fitted order. Explicit
|
n_4d |
numeric; the number of new observations to generate for the
dimensions higher than 2 (!) of a kD smooth (k >= 4). For example, if
the smooth is a 4D smooth, each of dimensions 3 and 4 will get |
unconditional |
logical; should confidence intervals include the
uncertainty due to smoothness selection? If |
overall_uncertainty |
logical; should the uncertainty in the model
constant term be included in the standard errors of smooth and parametric
effects? For parametric effects this includes the intercept variance and
its covariance with the term, without changing the partial estimates.
Each term uses the intercept of its own linear predictor.
Native scasm models are routed to |
constant |
numeric; a constant to add to the estimated values of the
smooth. |
fun |
function; a function that will be applied to the estimated values
and confidence interval before plotting. Can be a function or the name of a
function. For simultaneous bands it must be monotone over the entire band;
endpoint transformation alone does not preserve non-monotone band coverage.
Function |
dist |
numeric; if greater than 0, this is used to determine when
a location is too far from data to be plotted when plotting 2-D smooths.
The data are scaled into the unit square before deciding what to exclude,
and |
rug |
logical; draw a rug plot at the bottom of each plot for 1-D smooths or plot locations of data for higher dimensions. |
distinct_rug |
logical; should the data for the rug plots be reduced to the distinct values? |
contour |
logical; should contours be draw on the plot using
|
grouped_by |
Deprecated; use |
ci_alpha |
Deprecated; use |
ci_col |
Deprecated; use |
smooth_col |
Deprecated; use |
resid_col |
Deprecated; use |
contour_col |
Deprecated; use |
n_contour |
numeric; the number of contour bins. Will result in
|
partial_match |
logical; should smooths be selected by partial matches
with |
discrete_colour |
a suitable colour scale to be used when plotting discrete variables. |
discrete_fill |
a suitable fill scale to be used when plotting discrete variables. |
continuous_colour |
a suitable colour scale to be used when plotting continuous variables. |
continuous_fill |
a suitable fill scale to be used when plotting continuous variables. |
position |
Position adjustment, either as a string, or the result of a call to a position adjustment function. |
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
guides |
character; one of |
widths, heights
|
The relative widths and heights of each column and
row in the grid. Will get repeated to match the dimensions of the grid. If
there is more than 1 plot and |
crs |
the coordinate reference system (CRS) to use for the plot. All
data will be projected into this CRS. See |
default_crs |
the coordinate reference system (CRS) to use for non-sf
layers added to spherical plots. The default, |
lims_method |
character; affects how spherical plot axis limits are
determined. The default, |
wrap |
logical; wrap plots as a patchwork? If |
caption |
logical; show the smooth type in the caption of each plot? |
envir |
an optional environment for looking up data, functions and constants. Defaults to the model's evaluation environment. |
surface |
character; one of |
surface_3d |
named list of view options passed to |
ci_3d |
logical; add lower and upper interval surfaces to numeric
smooth and parametric effect panels when |
ci_3d_alpha |
Deprecated; use |
ci_3d_col |
Deprecated; use |
back_transform |
logical; plot covariates on their original scale?
Defaults to |
re_levels |
named list of factor level labels to retain in tensor products
with random-effect margins, for example |
mrf_plot |
character; display Markov random field smooths as area-labelled
estimates and intervals ( |
interval |
character; |
n_sim, n_cores
|
positive integers; coefficient draws and simulation cores for simultaneous bands. Parallel simulation requires OpenMP support. |
seed |
integer or |
interval_method |
character; "auto" uses stored scasm bootstrap draws
for pointwise intervals when available, and Gaussian intervals otherwise.
Use "gaussian" to request covariance-based limits or "bootstrap" to
require stored draws. Simultaneous bootstrap bands are not supported.
|
frequentist |
logical; use frequentist covariance for smooth-component intervals? The default uses approximate Bayesian covariance. Parametric effect intervals retain their existing Bayesian covariance calculation. |
shape_source |
character; initial uncertainty for |
... |
additional arguments passed to |
variables |
Character vector giving every covariate of the selected
smooths exactly once, in plotting order: x, y, then the conditioning
covariate for 3D smooths, or facet rows and columns for 4D smooths.
When supplied, selected smooths must use the same covariates. Use fitted coordinate names,
such as |
simultaneous_method |
character; calibration for simultaneous bands.
The default, |
simultaneous_domain |
numeric pair of increasing finite endpoints, or
a named list of such pairs keyed by spline coordinate. For tube bands,
|
tube_control |
named list controlling numerical tube calibration:
|
cyclic |
character; use Cartesian coordinates ( |
polar_args |
named list of options passed to |
grouped |
character or |
show_ci |
character or |
time_varying_style |
Display sdmTMB time-varying coefficients using
a line, points and interval ribbon ( |
centre |
character; for SCAM models, |
For models with multiple linear predictors, smooth and parametric plot
subtitles identify the model part for glmmTMB models or the distributional
parameter for mgcv models. Single-predictor models omit these automatic
labels; by-variable information and custom subtitles are still shown.
Constant glmmTMB dispersion
alone does not count as an additional predictor.
For example, gaulss() uses "Mean (mu)" and "Standard deviation (sigma)",
while twlss() uses "Mean (mu)", "Power (p)" and "Dispersion (phi)".
Shared smooths name each predictor to which they contribute. Families without
a known parameter mapping use numbered linear predictors. The existing smooth
titles and select values are unchanged, and all smooths are drawn by default.
By-variable information is appended to the default subtitle. Supply subtitle
through ... to replace it, or subtitle = "" to suppress it; NULL uses the
default. Custom title, xlab and ylab can also be supplied through ....
Parametric terms use the same predictor labels, including terms shared
across predictors. Saved parametric_effects() retain these labels.
Polar plots support cyclic cubic and cyclic P splines, including positive
cyclic P splines from scam, factor-by smooths and one-dimensional tensor
smooths with a cyclic margin. The covariate forms the angular axis and the
partial effect forms the radial axis, retaining their original numerical
values and units. By default the lower fitted cycle boundary is at twelve
o'clock, with values increasing clockwise. scales = "fixed" uses a common
radial effect range. Grouped smooths must have matching cycle boundaries.
The radial axis retains ggplot2's usual expansion, leaving space between
the interval band and the outer rug. Angular limits have no expansion.
Radial tick labels are inside the circle beside their grid rings by
default. Set polar_args = list(r.axis.inside = FALSE) to place them
outside, or supply a numeric covariate value to position the axis.
With automatic evaluation data, n points span both fitted cycle boundaries.
Supplied data and saved estimates keep their evaluation points, so partial
cycle coverage leaves a gap. Saved estimates require the cyclic_info
attribute returned by smooth_estimates(); recompute older estimates to
obtain fitted boundaries. Polar plots of transformed cyclic covariates
require back_transform = FALSE.
Random-effect tensor plots put continuous covariates before factors. Two
continuous covariates form a surface, with remaining factor levels and numeric
slices forming conditioning panels, consistently for te(), ti() and t2().
One continuous covariate gives curves for categorical combinations;
categorical-only terms give point ranges. Up to four covariates are supported.
Numeric conditioning slices use n_3d or n_4d. For factor conditioning
dimensions, these controls retain at most that many levels, taking the first
levels in fitted order. Explicit re_levels selections take precedence.
Supplied data and precomputed estimates retain their rows; select specific
factor levels with re_levels, or use data_slice() to fix conditioning
covariates. Observation layers do not introduce additional surface panels.
Three-dimensional faces retain the current diverging RdBu fill scale and
effect-range rules, shared across conditioning facets. continuous_fill
overrides the fill scale. Faces have no outlines; contour_col controls
contour lines. Estimate faces are fully opaque. Faces, contours, and floor
observations are depth-sorted together, so nearer faces hide the parts behind
them. The existing theme and facet styling are retained.
The first two displayed covariates form the horizontal axes, and the effect
(or standard error when requested) forms the vertical axis. Additional
covariates retain their existing conditioning facets: n_2d controls surface
resolution, while n_3d and n_4d control covariate slices. Fixed effect
ranges are also used for the vertical axis. With ci_3d = TRUE, translucent
lower and upper interval surfaces use the same mesh and masking as the
estimate. Their heights expand the vertical range, while the continuous
fill scale retains its existing range rules. ci_3d_alpha and ci_3d_col
style these surfaces separately from univariate interval ribbons.
Contours follow the displayed mesh, and available observations are projected onto its floor. Observations are not assigned to conditioning slices. Soap boundary loops are also projected onto the floor.
Supplied scattered evaluation data use piecewise-linear Delaunay triangles
and require the optional geometry package. Support masking and
soap-domain checks require sf. Faces crossing known excluded regions
are discarded conservatively. Fully masked slices remain empty; insufficient
non-collinear locations or conflicting heights at one location are errors.
The object returned is created by patchwork::wrap_plots().
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Internally, plots of each smooth are created using ggplot2::ggplot()
and composed into a single plot using patchwork::wrap_plots(). As a
result, it is not possible to use + to add to the plots in the way one
might typically work with ggplot() plots. Instead, use the & operator;
see the examples.
Gavin L. Simpson
load_mgcv() # Simulate data and fit a GAM df1 <- data_sim("eg1", n = 200, dist = "normal", scale = 2, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df1, method = "REML") # Plot all smooths draw(m1) # Draw a complete cycle in polar coordinates, using fitted knot boundaries m_cycle <- gam(y ~ s(x0, bs = "cc", k = 10), data = df1, knots = list(x0 = c(0, 1)), method = "REML") draw(m_cycle, cyclic = "polar") # See https://gavinsimpson.github.io/gratia/articles/custom-plotting.html # for more examples. Use the & operator to modify the theme of all panels.load_mgcv() # Simulate data and fit a GAM df1 <- data_sim("eg1", n = 200, dist = "normal", scale = 2, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df1, method = "REML") # Plot all smooths draw(m1) # Draw a complete cycle in polar coordinates, using fitted knot boundaries m_cycle <- gam(y ~ s(x0, bs = "cc", k = 10), data = df1, knots = list(x0 = c(0, 1)), method = "REML") draw(m_cycle, cyclic = "polar") # See https://gavinsimpson.github.io/gratia/articles/custom-plotting.html # for more examples. Use the & operator to modify the theme of all panels.
Provides draw() and assemble() methods for GAMLSS
and joint models fitted by GJRM::gamlss() or GJRM::gjrm(). assemble() returns the
individual plots; draw() arranges them using patchwork::wrap_plots().
## S3 method for class 'gamlss' draw( object, scales = c("free", "fixed"), ncol = NULL, nrow = NULL, guides = "keep", widths = NULL, heights = NULL, ..., n = 100, envir = NULL, select = NULL, parametric = NULL, terms = NULL, partial_match = FALSE, wrap = TRUE ) ## S3 method for class 'gamlss' assemble( object, scales = c("free", "fixed"), ..., residuals = FALSE, n = 100, envir = NULL, select = NULL, parametric = NULL, terms = NULL, partial_match = FALSE, grouped_by = deprecated(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz") ) ## S3 method for class 'gjrm' draw( object, scales = c("free", "fixed"), ncol = NULL, nrow = NULL, guides = "keep", widths = NULL, heights = NULL, ..., n = 100, envir = NULL, select = NULL, parametric = NULL, terms = NULL, partial_match = FALSE, wrap = TRUE ) ## S3 method for class 'gjrm' assemble( object, scales = c("free", "fixed"), ..., residuals = FALSE, n = 100, envir = NULL, select = NULL, parametric = NULL, terms = NULL, partial_match = FALSE, grouped_by = deprecated(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz") )## S3 method for class 'gamlss' draw( object, scales = c("free", "fixed"), ncol = NULL, nrow = NULL, guides = "keep", widths = NULL, heights = NULL, ..., n = 100, envir = NULL, select = NULL, parametric = NULL, terms = NULL, partial_match = FALSE, wrap = TRUE ) ## S3 method for class 'gamlss' assemble( object, scales = c("free", "fixed"), ..., residuals = FALSE, n = 100, envir = NULL, select = NULL, parametric = NULL, terms = NULL, partial_match = FALSE, grouped_by = deprecated(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz") ) ## S3 method for class 'gjrm' draw( object, scales = c("free", "fixed"), ncol = NULL, nrow = NULL, guides = "keep", widths = NULL, heights = NULL, ..., n = 100, envir = NULL, select = NULL, parametric = NULL, terms = NULL, partial_match = FALSE, wrap = TRUE ) ## S3 method for class 'gjrm' assemble( object, scales = c("free", "fixed"), ..., residuals = FALSE, n = 100, envir = NULL, select = NULL, parametric = NULL, terms = NULL, partial_match = FALSE, grouped_by = deprecated(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz") )
object |
a model fitted by |
scales |
character; should all univariate smooths be plotted with the
same y-axis scale? If Currently does not affect the y-axis scale of plots of the parametric terms. |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
guides |
character; one of |
widths, heights
|
The relative widths and heights of each column and
row in the grid. Will get repeated to match the dimensions of the grid. If
there is more than 1 plot and |
... |
arguments passed to |
n |
numeric; the number of points over the range of the covariate at which to evaluate a univariate smooth. |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
select |
Smooth selection across all equations, using the labels from
|
parametric |
logical or |
terms |
character; which model parametric terms should be drawn? The
Default of |
partial_match |
logical; in the case of character |
wrap |
Logical; return an assembled patchwork when |
residuals |
logical; should partial residuals for a smooth be drawn? Ignored for anything but a simple univariate smooth. If the model does not provide working residuals and working weights, warns once and draws the smooths without partial residuals. |
grouped_by |
Deprecated; use |
grouped |
character or |
show_ci |
character or |
assemble() and draw(wrap = FALSE) return a flat named list of
plots, ordered by equation and then by term within each equation. Smooth
names use the model-wide labels returned by smooths(). draw() returns
a patchwork by default. Both methods return invisible NULL when there
are no plots to draw.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
For models with multiple linear predictors, smooth and parametric
plot subtitles identify the distributional parameter using the parent
model's margin and equation order, rather than the working family of
the embedded GAMs.
Univariate GAMLSS models with one predictor omit these automatic labels.
Joint models retain equation labels even when only dependence is estimated.
Existing smooth labels, selection, by-variable information and custom
subtitles are retained.
Pass surface = "3d", ci_3d = TRUE through ... to add interval surfaces
to smooths and numeric parametric interactions in any equation.
ci_3d_alpha and ci_3d_col control their opacity and fill colour.
Pass cyclic = "polar" and optional polar_args through ... for
polar plots of supported one-dimensional cyclic smooths in any equation;
see draw.gam() for the coordinate options.
Joint models use the final joint coefficients and covariance for every
embedded GAM, including dependence equations and random-effect smooths.
Parametric plot subtitles also identify their response and parameter.
For both univariate and joint models, a parametric term repeated across
equations has list names such as x (equation 1) and x (equation 2);
unique terms keep their original names.
Grouped factor-by panels also receive an equation suffix when their
base name would hide another smooth's selection label.
Ordinal cutpoints are excluded from smooth and intercept uncertainty.
Fixed-margin fits plot their estimated dependence equation only.
Flexible survival equations fitted using SCAM are not yet supported.
Working residuals from preliminary GAM fits are unavailable for joint
models; requesting partial residuals warns and draws the smooths alone.
if (requireNamespace("GJRM", quietly = TRUE)) { load_mgcv() # Simulate a nonlinear mean with a binary group effect and Gaussian noise set.seed(0) n <- 100 x1 <- round(runif(n)) x2 <- runif(n) x3 <- runif(n) f1 <- function(x) cos(pi * 2 * x) + sin(pi * x) y1 <- -1.55 + 2 * x1 + f1(x2) + rnorm(n) dataSim <- data.frame(y1, x1, x2, x3) # Fit smooths for the mean and scale, then plot both model components m <- GJRM::gamlss(list(y1 ~ x1 + s(x2), ~ s(x3, k = 6)), data = dataSim) draw(m) }if (requireNamespace("GJRM", quietly = TRUE)) { load_mgcv() # Simulate a nonlinear mean with a binary group effect and Gaussian noise set.seed(0) n <- 100 x1 <- round(runif(n)) x2 <- runif(n) x3 <- runif(n) f1 <- function(x) cos(pi * 2 * x) + sin(pi * x) y1 <- -1.55 + 2 * x1 + f1(x2) + rnorm(n) dataSim <- data.frame(y1, x1, x2, x3) # Fit smooths for the mean and scale, then plot both model components m <- GJRM::gamlss(list(y1 ~ x1 + s(x2), ~ s(x3, k = 6)), data = dataSim) draw(m) }
Plots basis functions using ggplot2
## S3 method for class 'mgcv_smooth' draw( object, legend = FALSE, use_facets = TRUE, labeller = NULL, xlab, ylab, title = NULL, subtitle = NULL, caption = NULL, angle = NULL, ... )## S3 method for class 'mgcv_smooth' draw( object, legend = FALSE, use_facets = TRUE, labeller = NULL, xlab, ylab, title = NULL, subtitle = NULL, caption = NULL, angle = NULL, ... )
object |
an object, the result of a call to |
legend |
logical; should a legend by drawn to indicate basis functions? |
use_facets |
logical; for factor by smooths, use facets to show the
basis functions for each level of the factor? If |
labeller |
a labeller function with which to label facets. The default
is to use |
xlab |
character or expression; the label for the x axis. If not
supplied, a suitable label will be generated from |
ylab |
character or expression; the label for the y axis. If not
supplied, a suitable label will be generated from |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
... |
arguments passed to other methods. Not used by this method. |
A ggplot2::ggplot() object.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Gavin L. Simpson
load_mgcv() df <- data_sim("eg4", n = 400, seed = 42) bf <- basis(s(x0), data = df) draw(bf) bf <- basis(s(x2, by = fac, bs = "bs"), data = df) draw(bf)load_mgcv() df <- data_sim("eg4", n = 400, seed = 42) bf <- basis(s(x0), data = df) draw(bf) bf <- basis(s(x2, by = fac, bs = "bs"), data = df) draw(bf)
Plot concurvity measures
## S3 method for class 'pairwise_concurvity' draw( object, title = "Smooth-wise concurvity", subtitle = NULL, caption = NULL, x_lab = "Term", y_lab = "With", fill_lab = "Concurvity", continuous_colour = NULL, ... ) ## S3 method for class 'overall_concurvity' draw( object, title = "Overall concurvity", subtitle = NULL, caption = NULL, y_lab = "Concurvity", x_lab = NULL, bar_col = "steelblue", bar_fill = "steelblue", ... )## S3 method for class 'pairwise_concurvity' draw( object, title = "Smooth-wise concurvity", subtitle = NULL, caption = NULL, x_lab = "Term", y_lab = "With", fill_lab = "Concurvity", continuous_colour = NULL, ... ) ## S3 method for class 'overall_concurvity' draw( object, title = "Overall concurvity", subtitle = NULL, caption = NULL, y_lab = "Concurvity", x_lab = NULL, bar_col = "steelblue", bar_fill = "steelblue", ... )
object |
An object inheriting from class |
title |
character; the plot title. |
subtitle |
character; the plot subtitle. |
caption |
character; the plot caption |
x_lab |
character; the label for the x axis. |
y_lab |
character; the label for the y axis. |
fill_lab |
character; the label to use for the fill guide. |
continuous_colour |
function; continuous colour (fill) scale to use. |
... |
arguments passed to other methods. |
bar_col |
Deprecated; use |
bar_fill |
Deprecated; use |
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Plot estimated effects for model parametric terms
## S3 method for class 'parametric_effects' draw( object, scales = c("free", "fixed"), ci_level = 0.95, ci_col = "black", ci_alpha = 0.2, line_col = "black", constant = NULL, fun = NULL, rug = TRUE, position = "identity", angle = NULL, ..., ncol = NULL, nrow = NULL, guides = "keep", contour = TRUE, contour_col = "black", n_contour = NULL, surface = c("raster", "tile", "3d"), surface_3d = list(), ci_3d = FALSE, ci_3d_alpha = 0.15, ci_3d_col = "grey60", continuous_fill = NULL, discrete_colour = NULL, discrete_fill = NULL, back_transform = FALSE, time_varying_style = c("ribbon", "pointrange"), subtitle = NULL )## S3 method for class 'parametric_effects' draw( object, scales = c("free", "fixed"), ci_level = 0.95, ci_col = "black", ci_alpha = 0.2, line_col = "black", constant = NULL, fun = NULL, rug = TRUE, position = "identity", angle = NULL, ..., ncol = NULL, nrow = NULL, guides = "keep", contour = TRUE, contour_col = "black", n_contour = NULL, surface = c("raster", "tile", "3d"), surface_3d = list(), ci_3d = FALSE, ci_3d_alpha = 0.15, ci_3d_col = "grey60", continuous_fill = NULL, discrete_colour = NULL, discrete_fill = NULL, back_transform = FALSE, time_varying_style = c("ribbon", "pointrange"), subtitle = NULL )
object |
A |
scales |
Use a common effect-axis range for curves and points ( |
ci_level |
numeric between 0 and 1; the coverage of credible interval. |
ci_col |
Deprecated; use |
ci_alpha |
Deprecated; use |
line_col |
Deprecated; use |
constant |
numeric; a constant to add to the estimated values of the
smooth. |
fun |
function; a function that will be applied to the estimated values
and confidence interval before plotting. Can be a function or the name of a
function. For simultaneous bands it must be monotone over the entire band;
endpoint transformation alone does not preserve non-monotone band coverage.
Function |
rug |
logical; draw a rug plot at the bottom of each plot for 1-D smooths or plot locations of data for higher dimensions. |
position |
Position adjustment, either as a string, or the result of a call to a position adjustment function. |
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
... |
additional arguments passed to |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
guides |
character; one of |
contour |
logical; should contours be draw on the plot using
|
contour_col |
Deprecated; use |
n_contour |
numeric; the number of contour bins. Will result in
|
surface |
character; one of |
surface_3d |
named list of view options passed to |
ci_3d |
logical; add lower and upper interval surfaces to numeric
smooth and parametric effect panels when |
ci_3d_alpha |
Deprecated; use |
ci_3d_col |
Deprecated; use |
continuous_fill |
a suitable fill scale to be used when plotting continuous variables. |
discrete_colour |
a suitable colour scale to be used when plotting discrete variables. |
discrete_fill |
a suitable fill scale to be used when plotting discrete variables. |
back_transform |
logical; plot covariates on their original scale?
Defaults to |
time_varying_style |
Display sdmTMB time-varying coefficients using
a line, points and interval ribbon ( |
subtitle |
Character or expression; replace the automatic predictor
subtitle on every panel. |
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
ggplot
Displays the penalty matrices of smooths as a heatmap using ggplot
## S3 method for class 'penalty_df' draw( object, normalize = FALSE, as_matrix = TRUE, continuous_fill = NULL, xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ncol = NULL, nrow = NULL, guides = "keep", geom = c("raster", "tile"), ... )## S3 method for class 'penalty_df' draw( object, normalize = FALSE, as_matrix = TRUE, continuous_fill = NULL, xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ncol = NULL, nrow = NULL, guides = "keep", geom = c("raster", "tile"), ... )
object |
a fitted GAM, the result of a call to |
normalize |
logical; normalize the penalty to the range -1, 1? |
as_matrix |
logical; how should the plotted penalty matrix be oriented?
If |
continuous_fill |
a suitable fill scale to be used when plotting continuous variables. |
xlab |
character or expression; the label for the x axis. If not supplied, no axis label will be drawn. May be a vector, one per penalty. |
ylab |
character or expression; the label for the y axis. If not supplied, no axis label will be drawn. May be a vector, one per penalty. |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots. |
guides |
character; one of |
geom |
character; either |
... |
additional arguments passed to |
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
load_mgcv() # Fit different spline bases to simulated Gaussian responses dat <- data_sim("eg1", n = 200, seed = 42) m <- gam(y ~ s(x0) + s(x1, bs = "cr") + s(x2, bs = "bs"), data = dat, method = "REML") # Display the penalty matrices for the fitted smooths draw(penalty(m))load_mgcv() # Fit different spline bases to simulated Gaussian responses dat <- data_sim("eg1", n = 200, seed = 42) m <- gam(y ~ s(x0) + s(x1, bs = "cr") + s(x2, bs = "bs"), data = dat, method = "REML") # Display the penalty matrices for the fitted smooths draw(penalty(m))
A rootogram is a model diagnostic tool that assesses the goodness of fit of
a statistical model. The observed values of the response are compared with
those expected from the fitted model. For discrete, count responses, the
frequency of each count (0, 1, 2, etc) in the observed data and expected
from the conditional distribution of the response implied by the model are
compared. For continuous variables, the observed and expected frequencies
are obtained by grouping the data into bins. The rootogram is drawn using
ggplot2::ggplot() graphics. The design closely follows Kleiber & Zeileis
(2016).
## S3 method for class 'rootogram' draw( object, type = c("hanging", "standing", "suspended"), sqrt = TRUE, ref_line = TRUE, warn_limits = TRUE, fitted_colour = "steelblue", bar_colour = NA, bar_fill = "grey", ref_line_colour = "black", warn_line_colour = "black", ylab = NULL, xlab = NULL, ... )## S3 method for class 'rootogram' draw( object, type = c("hanging", "standing", "suspended"), sqrt = TRUE, ref_line = TRUE, warn_limits = TRUE, fitted_colour = "steelblue", bar_colour = NA, bar_fill = "grey", ref_line_colour = "black", warn_line_colour = "black", ylab = NULL, xlab = NULL, ... )
object |
and R object to plot. |
type |
character; the type of rootogram to draw. |
sqrt |
logical; show the observed and fitted frequencies |
ref_line |
logical; draw a reference line at zero? |
warn_limits |
logical; draw Tukey's warning limit lines at +/- 1? |
fitted_colour, bar_colour, bar_fill, ref_line_colour, warn_line_colour
|
Deprecated; use |
xlab, ylab
|
character; labels for the x and y axis of the rootogram.
May be missing ( |
... |
arguments passed to other methods. |
A 'ggplot' object.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Kleiber, C., Zeileis, A., (2016) Visualizing Count Data Regressions Using Rootograms. Am. Stat. 70, 296–303. doi:10.1080/00031305.2016.1173590
rootogram() to compute the data for the rootogram.
load_mgcv() df <- data_sim("eg1", n = 1000, dist = "poisson", scale = 0.1, seed = 6) # A poisson example m <- gam(y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, bs = "cr") + s(x3, bs = "cr"), family = poisson(), data = df, method = "REML") rg <- rootogram(m) # plot the rootogram draw(rg) # change the type of rootogram draw(rg, type = "suspended")load_mgcv() df <- data_sim("eg1", n = 1000, dist = "poisson", scale = 0.1, seed = 6) # A poisson example m <- gam(y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, bs = "cr") + s(x3, bs = "cr"), family = poisson(), data = df, method = "REML") rg <- rootogram(m) # plot the rootogram draw(rg) # change the type of rootogram draw(rg, type = "suspended")
Native ggplot2 displays of retained coefficient chains. Trace plots show movement over iterations, including repeated values after MH rejections. Rank plots compare overlaid histogram outlines for the ranks of each coefficient pooled across chains. Chains exploring the same distribution should have approximately uniform rank histograms. These plots complement the numerical summaries; similar-looking chains alone do not establish convergence.
## S3 method for class 'sampling_diagnostics' draw( object, type = c("trace", "rank"), select = NULL, n_bins = 20L, scales = NULL, ncol = NULL, nrow = NULL, alpha = 0.7, linewidth = 0.4, discrete_colour = NULL, ... )## S3 method for class 'sampling_diagnostics' draw( object, type = c("trace", "rank"), select = NULL, n_bins = 20L, scales = NULL, ncol = NULL, nrow = NULL, alpha = 0.7, linewidth = 0.4, discrete_colour = NULL, ... )
object |
A |
type |
Either |
select |
Coefficients to plot, as exact names, positive integer positions, or a logical vector with one entry per coefficient. The default plots every available coefficient. |
n_bins |
Positive integer; number of common pooled-rank bins. Used only for rank plots. Tied draws receive their average rank, without jitter. |
scales |
Facet scales, either |
ncol, nrow
|
Number of columns or rows in the panel layout. |
alpha |
Deprecated; use |
linewidth |
Deprecated; use |
discrete_colour |
An optional ggplot2 discrete colour scale. Defaults follow gratia's smooth plots: Okabe-Ito for up to nine chains, then hue. |
... |
Additional arguments passed to |
The trace x axis counts retained iterations within each chain, rather than the globally unique draw number. Burn-in is discarded by the samplers and cannot be displayed. With thinning, successive plotted iterations represent successive retained draws, not successive MH transitions.
Rank plots require at least two chains. Ranks are computed separately for each selected coefficient, pooling all chains. A dashed line shows the average count per bin. Independent continuous draws from the same distribution should give approximately flat histograms. Autocorrelation and ties affect the histogram variation; the reference line is not a confidence bound.
Plots always describe coefficient draws, including when diagnostics are
extracted from response samples or smooths. For transformed quantities use
as_mcmc_draws() with external diagnostic tools. Sampling with
diagnostics = TRUE retains coefficient draws for plotting from those
outputs. Coefficient matrices can be plotted whenever their sampling
metadata are available, even without numerical diagnostic summaries.
A ggplot2::ggplot() object.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
sampling_diagnostics(), as_mcmc_draws()
load_mgcv() dat <- data_sim("eg1", n = 100, seed = 42) model <- gam(y ~ s(x0, k = 5), data = dat, method = "REML") b <- post_draws(model, n_draws = 400, chains = 4, method = "mh", burnin = 100, seed = 281) diagnostics <- sampling_diagnostics(b) draw(diagnostics, select = 1:2) draw(diagnostics, type = "rank", select = 1:2, n_bins = 10)load_mgcv() dat <- data_sim("eg1", n = 100, seed = 42) model <- gam(y ~ s(x0, k = 5), data = dat, method = "REML") b <- post_draws(model, n_draws = 400, chains = 4, method = "mh", burnin = 100, seed = 281) diagnostics <- sampling_diagnostics(b) draw(diagnostics, select = 1:2) draw(diagnostics, type = "rank", select = 1:2, n_bins = 10)
smooth_estimates()
Plot the result of a call to smooth_estimates()
## S3 method for class 'smooth_estimates' draw( object, constant = NULL, fun = NULL, contour = TRUE, grouped_by = deprecated(), contour_col = "black", n_contour = NULL, ci_alpha = 0.2, ci_col = "black", smooth_col = "black", resid_col = "steelblue3", decrease_col = "#56B4E9", increase_col = "#E69F00", change_lwd = 1.75, partial_match = FALSE, discrete_colour = NULL, discrete_fill = NULL, continuous_colour = NULL, continuous_fill = NULL, angle = NULL, ylim = NULL, crs = NULL, default_crs = NULL, lims_method = "geometry_bbox", caption = TRUE, surface = c("raster", "tile", "3d"), surface_3d = list(), ci_3d = FALSE, ci_3d_alpha = 0.15, ci_3d_col = "grey60", back_transform = FALSE, re_levels = NULL, mrf_plot = c("effects", "qq"), interval = NULL, ..., variables = NULL, cyclic = c("cartesian", "polar"), polar_args = list(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz") )## S3 method for class 'smooth_estimates' draw( object, constant = NULL, fun = NULL, contour = TRUE, grouped_by = deprecated(), contour_col = "black", n_contour = NULL, ci_alpha = 0.2, ci_col = "black", smooth_col = "black", resid_col = "steelblue3", decrease_col = "#56B4E9", increase_col = "#E69F00", change_lwd = 1.75, partial_match = FALSE, discrete_colour = NULL, discrete_fill = NULL, continuous_colour = NULL, continuous_fill = NULL, angle = NULL, ylim = NULL, crs = NULL, default_crs = NULL, lims_method = "geometry_bbox", caption = TRUE, surface = c("raster", "tile", "3d"), surface_3d = list(), ci_3d = FALSE, ci_3d_alpha = 0.15, ci_3d_col = "grey60", back_transform = FALSE, re_levels = NULL, mrf_plot = c("effects", "qq"), interval = NULL, ..., variables = NULL, cyclic = c("cartesian", "polar"), polar_args = list(), grouped = c("sz", "fs"), show_ci = c("factor-by", "sz") )
object |
a fitted GAM, the result of a call to |
constant |
numeric; a constant to add to the estimated values of the
smooth. |
fun |
function; a function that will be applied to the estimated values
and confidence interval before plotting. Can be a function or the name of a
function. For simultaneous bands it must be monotone over the entire band;
endpoint transformation alone does not preserve non-monotone band coverage.
Function |
contour |
logical; should contours be draw on the plot using
|
grouped_by |
Deprecated; use |
contour_col |
Deprecated; use |
n_contour |
numeric; the number of contour bins. Will result in
|
ci_alpha |
Deprecated; use |
ci_col |
Deprecated; use |
smooth_col |
Deprecated; use |
resid_col |
Deprecated; use |
decrease_col, increase_col
|
Deprecated; use |
change_lwd |
Deprecated; use |
partial_match |
logical; should smooths be selected by partial matches
with |
discrete_colour |
a suitable colour scale to be used when plotting discrete variables. |
discrete_fill |
a suitable fill scale to be used when plotting discrete variables. |
continuous_colour |
a suitable colour scale to be used when plotting continuous variables. |
continuous_fill |
a suitable fill scale to be used when plotting continuous variables. |
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
ylim |
numeric; vector of y axis limits to use all all panels drawn. |
crs |
the coordinate reference system (CRS) to use for the plot. All
data will be projected into this CRS. See |
default_crs |
the coordinate reference system (CRS) to use for non-sf
layers added to spherical plots. The default, |
lims_method |
character; affects how spherical plot axis limits are
determined. The default, |
caption |
logical; show the smooth type in the caption of each plot? |
surface |
character; one of |
surface_3d |
named list of view options passed to |
ci_3d |
logical; add lower and upper interval surfaces to numeric
smooth and parametric effect panels when |
ci_3d_alpha |
Deprecated; use |
ci_3d_col |
Deprecated; use |
back_transform |
logical; plot covariates on their original scale?
Defaults to |
re_levels |
named list of factor level labels to retain in tensor products
with random-effect margins, for example |
mrf_plot |
character; display Markov random field smooths as area-labelled
estimates and intervals ( |
interval |
character or |
... |
additional arguments passed to |
variables |
Character vector giving every covariate of the selected
smooths exactly once, in plotting order: x, y, then the conditioning
covariate for 3D smooths, or facet rows and columns for 4D smooths.
When supplied, selected smooths must use the same covariates. Use fitted coordinate names,
such as |
cyclic |
character; use Cartesian coordinates ( |
polar_args |
named list of options passed to |
grouped |
character or |
show_ci |
character or |
cyclic = "polar" uses fitted cycle boundaries stored in the
cyclic_info attribute. Evaluation points are unchanged: estimates
covering only part of a cycle leave a gap. To draw a complete cycle,
supply both fitted boundary values when computing estimates, or use
draw(model, cyclic = "polar") to generate the full-cycle grid.
Recompute older saved estimates with smooth_estimates() if their
fitted cycle boundaries are unavailable. See draw.gam() for supported
smooths and coordinate options.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
load_mgcv() # Simulate an additive Gaussian response and fit a GAM df <- data_sim("eg1", n = 200, seed = 21) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # Evaluate one smooth and plot its estimates and interval sm <- smooth_estimates(m, select = "s(x2)") draw(sm)load_mgcv() # Simulate an additive Gaussian response and fit a GAM df <- data_sim("eg1", n = 200, seed = 21) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # Evaluate one smooth and plot its estimates and interval sm <- smooth_estimates(m, select = "s(x2)") draw(sm)
Plot posterior smooths
## S3 method for class 'smooth_samples' draw( object, select = NULL, n_samples = NULL, seed = NULL, xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, alpha = 1, colour = "black", contour = FALSE, contour_col = "black", n_contour = NULL, scales = c("free", "fixed"), rug = TRUE, partial_match = FALSE, angle = NULL, ncol = NULL, nrow = NULL, guides = "keep", ... )## S3 method for class 'smooth_samples' draw( object, select = NULL, n_samples = NULL, seed = NULL, xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, alpha = 1, colour = "black", contour = FALSE, contour_col = "black", n_contour = NULL, scales = c("free", "fixed"), rug = TRUE, partial_match = FALSE, angle = NULL, ncol = NULL, nrow = NULL, guides = "keep", ... )
object |
a fitted GAM, the result of a call to |
select |
character, logical, or numeric; which smooths to plot. If
|
n_samples |
numeric; if not |
seed |
numeric; random seed to be used to if sampling draws. |
xlab |
character or expression; the label for the x axis. If not
supplied, a suitable label will be generated from |
ylab |
character or expression; the label for the y axis. If not
supplied, a suitable label will be generated from |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
alpha |
Deprecated; use |
colour |
Deprecated; use |
contour |
logical; should contour lines be added to smooth surfaces? |
contour_col |
Deprecated; use |
n_contour |
numeric; the number of contour bins. Will result in
|
scales |
character; should all univariate smooths be plotted with the
same y-axis scale? If Currently does not affect the y-axis scale of plots of the parametric terms. |
rug |
logical; draw a rug plot at the bottom of each plot for 1-D smooths or plot locations of data for higher dimensions. |
partial_match |
logical; should smooths be selected by partial matches
with |
angle |
numeric; the angle at which the x axis tick labels are to be
drawn passed to the |
ncol, nrow
|
numeric; the numbers of rows and columns over which to spread the plots |
guides |
character; one of |
... |
arguments to be passed to |
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
Gavin L. Simpson
load_mgcv() # Simulate an additive Gaussian response and fit a GAM dat <- data_sim("eg1", n = 200, scale = 1, seed = 1) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # Draw 15 possible curves for the smooth of x2 on a 100-point grid sm <- smooth_samples(m, select = "s(x2)", n_grid = 100, n_draws = 15, seed = 23478) draw(sm)load_mgcv() # Simulate an additive Gaussian response and fit a GAM dat <- data_sim("eg1", n = 200, scale = 1, seed = 1) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") # Draw 15 possible curves for the smooth of x2 on a 100-point grid sm <- smooth_samples(m, select = "s(x2)", n_grid = 100, n_draws = 15, seed = 23478) draw(sm)
Draw estimates and their stored confidence intervals, with components on the x-axis by default. No model fitting or posterior sampling is performed.
## S3 method for class 'variance_comp' draw( object, type = c("variance", "std_dev", "proportion"), select = NULL, include_total = TRUE, predictor = NULL, ncol = NULL, nrow = NULL, angle = NULL, n_dodge = 1L, flip = FALSE, ... )## S3 method for class 'variance_comp' draw( object, type = c("variance", "std_dev", "proportion"), select = NULL, include_total = TRUE, predictor = NULL, ncol = NULL, nrow = NULL, angle = NULL, n_dodge = 1L, flip = FALSE, ... )
object |
A result from |
type |
What to plot: |
select |
Components to plot, as exact names, positive integer positions,
or a logical vector with one entry per row of |
include_total |
Logical; include the total rows of term results?
Defaults to |
predictor |
Linear predictors to plot for |
ncol, nrow
|
Number of columns or rows for the panels. |
angle |
Numeric; angle of the component labels in degrees, between
-90 and 90. Passed to |
n_dodge |
Positive integer; number of rows for component labels, or
columns with |
flip |
Logical; put components on the y-axis? Defaults to |
... |
Not used. Modify the returned plot with ggplot2 layers, scales and themes. |
Variance plots square the stored standard-deviation interval bounds so that estimates and intervals use the same scale. Standard-deviation and proportion plots use their stored bounds directly. Components with unavailable intervals retain their points. Intervals are drawn when both bounds are finite. Undefined estimates have no point, but retain their component labels.
Proportions can be negative or greater than one, and the plot preserves those values. Each panel shows only terms belonging to that predictor and its own total. A predictor with zero total variance has undefined proportions and is displayed without points or intervals.
Points use the geom.gratia.effect theme element and intervals use
geom.gratia.interval; see gratia_theme_get().
A ggplot2::ggplot() object.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
variance_comp(), gratia_theme_get()
load_mgcv() # Simulate linear and nonlinear effects with Gaussian noise set.seed(42) dat <- data.frame(x = runif(120), z = runif(120)) dat$y <- 2 * dat$z + sin(2 * pi * dat$x) + rnorm(120, sd = 0.3) # Fit a linear effect of z and a smooth effect of x model <- gam(y ~ z + s(x, k = 8), data = dat, method = "REML") # Plot the variances used in the random-effect representation of the penalties components <- variance_comp(model) draw(components) # Plot variation of fitted term contributions across the fitting observations terms <- variance_comp(model, type = "terms", n_draws = 200, seed = 42) draw(terms)load_mgcv() # Simulate linear and nonlinear effects with Gaussian noise set.seed(42) dat <- data.frame(x = runif(120), z = runif(120)) dat$y <- 2 * dat$z + sin(2 * pi * dat$x) + rnorm(120, sd = 0.3) # Fit a linear effect of z and a smooth effect of x model <- gam(y ~ z + s(x, k = 8), data = dat, method = "REML") # Plot the variances used in the random-effect representation of the penalties components <- variance_comp(model) draw(components) # Plot variation of fitted term contributions across the fitting observations terms <- variance_comp(model, type = "terms", n_draws = 200, seed = 42) draw(terms)
Extracts the effective degrees of freedom (EDF) for model smooth terms or overall EDF for fitted GAMs
edf(object, ...) ## S3 method for class 'gam' edf( object, select = NULL, smooth = deprecated(), type = c("default", "unconditional", "alternative"), partial_match = FALSE, ... ) model_edf(object, ..., type = c("default", "unconditional", "alternative")) ## S3 method for class 'gamm4' edf(object, ...) ## S3 method for class 'scam' edf(object, ..., type = c("default", "unconditional", "alternative"))edf(object, ...) ## S3 method for class 'gam' edf( object, select = NULL, smooth = deprecated(), type = c("default", "unconditional", "alternative"), partial_match = FALSE, ... ) model_edf(object, ..., type = c("default", "unconditional", "alternative")) ## S3 method for class 'gamm4' edf(object, ...) ## S3 method for class 'scam' edf(object, ..., type = c("default", "unconditional", "alternative"))
object |
a fitted model from which to extract smooth-specific EDFs. |
... |
arguments passed to methods. |
select |
character, logical, or numeric; which smooths EDF to extract.
If |
smooth |
|
type |
character: which type of EDF to return. |
partial_match |
logical; should smooths be selected by partial matches
with |
Multiple formulations for the effective degrees of freedom are
available. The additional uncertainty due to selection of smoothness
parameters can be taken into account when computing the EDF of smooths.
This form of the EDF is available with type = "unconditional".
Wood (2017; pp. 252) describes an alternative EDF for the model
where
is the matrix trace and is a matrix
mapping unpenalised coefficient estimates to the penalized coefficient
estimates. The trace of is effectively the average
shrinkage of the coefficients multiplied by the number of coefficients
(Wood, 2017). Smooth-specific EDFs then are obtained by summing up the
relevant elements of .
load_mgcv() df <- data_sim("eg1", n = 400, seed = 42) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # extract the EDFs for all smooths edf(m) # or selected smooths edf(m, select = c("s(x0)", "s(x2)")) # accounting for smoothness parameter uncertainty edf(m, type = "unconditional") # over EDF of the model, including the intercept model_edf(m) # can get model EDF for multiple models m2 <- gam(y ~ s(x0) + s(x1) + s(x3), data = df, method = "REML") model_edf(m, m2)load_mgcv() df <- data_sim("eg1", n = 400, seed = 42) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # extract the EDFs for all smooths edf(m) # or selected smooths edf(m, select = c("s(x0)", "s(x2)")) # accounting for smoothness parameter uncertainty edf(m, type = "unconditional") # over EDF of the model, including the intercept model_edf(m) # can get model EDF for multiple models m2 <- gam(y ~ s(x0) + s(x1) + s(x3), data = df, method = "REML") model_edf(m, m2)
S3 methods to evaluate individual smooths
eval_smooth(smooth, ...) ## S3 method for class 'mgcv.smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'soap.film' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, clip = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'scam_smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'fs.interaction' eval_smooth( smooth, model, n = 100, n_2d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'sz.interaction' eval_smooth( smooth, model, n = 100, n_2d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'random.effect' eval_smooth( smooth, model, n = 100, n_2d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'mrf.smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 't2.smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'tensor.smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, envir = NULL, back_transform = FALSE, ... )eval_smooth(smooth, ...) ## S3 method for class 'mgcv.smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'soap.film' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, clip = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'scam_smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'fs.interaction' eval_smooth( smooth, model, n = 100, n_2d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'sz.interaction' eval_smooth( smooth, model, n = 100, n_2d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'random.effect' eval_smooth( smooth, model, n = 100, n_2d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'mrf.smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 't2.smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, envir = NULL, back_transform = FALSE, ... ) ## S3 method for class 'tensor.smooth' eval_smooth( smooth, model, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, envir = NULL, back_transform = FALSE, ... )
smooth |
currently an object that inherits from class |
... |
arguments passed to other methods |
model |
a fitted model; currently only |
n |
numeric; the number of points over the range of the covariate at which to evaluate a univariate smooth. |
n_2d |
numeric; the number of points along each of the first two axes
of a smooth surface, including surface panels of higher-dimensional smooths.
The default is 50 in plotting and plot-preparation functions. If |
n_3d, n_4d
|
numeric; the number of points along the third axis of a
3D smooth ( |
data |
an optional data frame of values to evaluate |
unconditional |
logical; if |
frequentist |
logical; if |
overall_uncertainty |
logical; should the uncertainty in the model constant term be included in the standard error of the evaluate values of the smooth? |
dist |
numeric; if greater than 0, this is used to determine when
a location is too far from data to be plotted when plotting 2-D smooths.
The data are scaled into the unit square before deciding what to exclude,
and |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
back_transform |
logical; generate automatic grids on the original
covariate scale? The default, |
clip |
logical; should evaluation points be clipped to the boundary of
a soap film smooth? The default is |
Returns values of parametric model terms
at values of factor terms and over a grid of covariate values for linear
parametric terms. This function is now deprecated in favour of
parametric_effects().
evaluate_parametric_term(object, ...) ## S3 method for class 'gam' evaluate_parametric_term(object, term, unconditional = FALSE, ...) ## S3 method for class 'gamm4' evaluate_parametric_term(object, ...)evaluate_parametric_term(object, ...) ## S3 method for class 'gam' evaluate_parametric_term(object, term, unconditional = FALSE, ...) ## S3 method for class 'gamm4' evaluate_parametric_term(object, ...)
object |
an object of class |
... |
arguments passed to other methods. |
term |
character; which parametric term whose effects are evaluated |
unconditional |
logical; should confidence intervals include the
uncertainty due to smoothness selection? If |
Evaluate a smooth at a grid of evenly
spaced value over the range of the covariate associated with the smooth.
Alternatively, a set of points at which the smooth should be evaluated can be
supplied.
evaluate_smooth(object, ...)evaluate_smooth(object, ...)
object |
an object of class |
... |
arguments passed to other methods. |
evaluate_smooth() is deprecated in
favour of smooth_estimates(), which provides a cleaner way to evaluate a
smooth over a range of covariate values. smooth_estimates() can handle a
much wider range of models than evaluate_smooth() is capable of and
smooth_estimates() is much easier to extend to handle new smooth types.
Most code that uses evaluate_smooth() should work simply by changing the
function call to smooth_estimates(). However, there are some differences:
the newdata argument becomes data
A data frame, which is of class "evaluated_1d_smooth" or
evaluated_2d_smooth, which inherit from classes "evaluated_smooth"
and "data.frame".
For a continuous vector x, evenly and seq_min_max()
create a sequence of n evenly-spaced values over the range lower
– upper. By default, lower is defined as min(x) and upper as
max(x), excluding NAs. For a factor x, the function returns
each level once as a factor, preserving its levels and ordered status.
all_levels() is an alias of evenly() with a name intended for factors.
evenly(x, n = 100, by = NULL, lower = NULL, upper = NULL) all_levels(x, n = 100, by = NULL, lower = NULL, upper = NULL) seq_min_max(x, n, by = NULL, lower = NULL, upper = NULL)evenly(x, n = 100, by = NULL, lower = NULL, upper = NULL) all_levels(x, n = 100, by = NULL, lower = NULL, upper = NULL) seq_min_max(x, n, by = NULL, lower = NULL, upper = NULL)
x |
numeric or factor; vector over which evenly-spaced values or factor levels are returned. |
n |
numeric; the number of evenly-spaced values to return. A default of
|
by |
numeric; the increment of the sequence. If specified, argument |
lower |
numeric; the lower bound of the interval. |
upper |
numeric; the upper bound of the interval. |
A numeric vector of length n, or a factor containing each level of
x once, with the same levels and ordered status as x.
See base::seq() for details of the behaviour of evenly() when
using by.
x <- rnorm(10) n <- 10L # 10 values evenly over the range of `x` evenly(x, n = n) # evenly spaced values, incrementing by 0.2 evenly(x, by = 0.2) # evenly spaced values, incrementing by 0.2, starting at -2 evenly(x, by = 0.2, lower = -2)x <- rnorm(10) n <- 10L # 10 values evenly over the range of `x` evenly(x, n = n) # evenly spaced values, incrementing by 0.2 evenly(x, by = 0.2) # evenly spaced values, incrementing by 0.2, starting at -2 evenly(x, by = 0.2, lower = -2)
All combinations of factor levels
factor_combos(object, ...) ## S3 method for class 'gam' factor_combos(object, vars = everything(), complete = TRUE, ...) ## S3 method for class 'gamm4' factor_combos(object, ...)factor_combos(object, ...) ## S3 method for class 'gam' factor_combos(object, vars = everything(), complete = TRUE, ...) ## S3 method for class 'gamm4' factor_combos(object, ...)
object |
a fitted model object. |
... |
arguments passed to methods. |
vars |
terms to include or exclude from the returned object. Uses tidyselect principles. |
complete |
logical; should all combinations of factor levels be
returned? If |
A family can supply a gratia_diagnostics function to describe its response
distribution without adding family-name checks to gratia. The function is
called with named arguments mu, wt, scale, y and eta. These contain
response parameters, weights, fitted scale, the fitting response and linear
predictors, respectively. Diagnostics use fitted parameters and sampling
weights; log_lik() uses draw-specific parameters and likelihood weights.
Missing fitting rows have been removed;
grouped families receive only their own rows. eta can be NULL when a
distribution is constructed without a fitted model.
Return a named list. Omitted fields retain gratia's existing family defaults;
an explicit NULL removes an optional function or moment. Existing $rd,
$cdf and $qf functions are preserved and supplied with their usual mgcv
arguments. Replacement functions in the returned list instead capture fitted
parameters and use the following interface:
mean, variance: numeric response moments, one per observation. A matrix
is allowed for multiple response columns. Use the full response expectation,
rather than a location parameter or a component mean.
cdf, cdf_left: functions (q, log_p = FALSE, lower_tail = TRUE) for
P(Y <= q) and P(Y < q), respectively. They must support both tails and
logarithms. For an upper tail, cdf_left returns P(Y >= q).
qf: a function (p, log_p = FALSE, lower_tail = TRUE) for quantiles.
rd: a function with no arguments that draws a complete response vector
(or response matrix), retaining any dependence between observations.
log_lik: a function (y) returning one normalised log density or log
probability mass per observation, including fitting weights. A response
vector contributes one value; a multivariate response contributes one joint
value per row. log_lik() calls the factory at each coefficient draw with
likelihood weights, which can differ from diagnostic sampling weights.
Parameters represented by mu and eta vary with that draw; the hook must
exclude smoothing penalties and priors. Finite positive log densities and
-Inf for impossible observations are allowed; missing values and Inf
are invalid.
bounds: a function (y) returning a list with numeric lower and upper
response bounds. Censoring intervals use their endpoints. Exact count
observations can use y - 1 and y. Alternatively, supply cdf_left:
gratia then randomises between P(Y < y) and P(Y <= y) automatically.
A bounds list may also supply cdf_lower and cdf_upper, functions
(log_p = FALSE, lower_tail = TRUE) that evaluate its endpoint probabilities,
and left_limit, a logical vector marking rows to randomise at equal bounds.
continuous: set to TRUE to declare that responses have no probability
masses. An unfamiliar grouped-family component must supply bounds,
cdf_left, or this declaration before using PIT/quantile residuals.
diagnostic_residuals: a function (y, type) for observed and reference
deviance, response and Pearson residuals. Otherwise the family's existing
residual method is used.
observe: a function (y) applying an observation process, such as known
censoring thresholds, to generated responses before traditional QQ/worm
reference residuals are calculated. Return the response encoding expected
by the family's residual method. This function is not applied to fitting
observations or to the public response and posterior samplers.
reference_available, reference_reason: a single logical value and an
explanation. Set availability to FALSE when traditional distribution-based
references cannot be generated, for example when censoring thresholds are
unknown. Analytic PIT/quantile plots remain available.
mean_available, variance_available, moment_reason: single logical
values specifying whether the population moments exist, and an explanation
used when a requested residual requires an undefined moment.
independent, joint_available, dependence_reason: single logical values
describing independence and availability of joint response draws, and an
explanation of dependence. joint_available requires an rd function.
approximation: an optional explanation shown in diagnostic subtitles.
Functions must return one value per response in fitting order. Probabilities must be valid and lower bounds must not exceed upper bounds. gratia validates supplied values and reports errors instead of silently using another method. The factory is called again for each prepared distribution; avoid changing the family or drawing random numbers in the factory itself.
Adding this function does not extend a family's supported fitting methods. Posterior predictive sampling still uses the fitting package's parameter and response sampling methods. The likelihood hook also operates at supplied coefficient draws.
diagnostic_support, quantile_residuals(), appraise()
load_mgcv() f <- poisson() f$gratia_diagnostics <- function(mu, wt, scale, y, eta) { list(mean = mu, variance = mu, cdf_left = function(q, log_p = FALSE, lower_tail = TRUE) { ppois(ceiling(q) - 1, lambda = mu, log.p = log_p, lower.tail = lower_tail) }) } dat <- data.frame(x = seq(0, 1, length.out = 40)) dat$y <- rep(c(0, 1, 2, 4), 10) f$rd <- function(mu, wt, scale) rpois(length(mu), mu) f$qf <- function(p, mu, wt, scale) qpois(p, mu) f$cdf <- function(q, mu, wt, scale) ppois(q, mu) fit <- gam(y ~ x, data = dat, family = f, method = "REML") qq_plot(fit, type = "quantile", seed = 1)load_mgcv() f <- poisson() f$gratia_diagnostics <- function(mu, wt, scale, y, eta) { list(mean = mu, variance = mu, cdf_left = function(q, log_p = FALSE, lower_tail = TRUE) { ppois(ceiling(q) - 1, lambda = mu, log.p = log_p, lower.tail = lower_tail) }) } dat <- data.frame(x = seq(0, 1, length.out = 40)) dat$y <- rep(c(0, 1, 2, 4), 10) f$rd <- function(mu, wt, scale) rpois(length(mu), mu) f$qf <- function(p, mu, wt, scale) qpois(p, mu) f$cdf <- function(q, mu, wt, scale) ppois(q, mu) fit <- gam(y ~ x, data = dat, family = f, method = "REML") qq_plot(fit, type = "quantile", seed = 1)
Extracts the name of the family used to fit the supplied model.
family_name(object, ...)family_name(object, ...)
object |
an R object. |
... |
arguments passed to other methods. |
A character vector containing the family name.
Inspect the meaning and order of distribution parameters independently of the numerical representation used by the fitting package.
family_parameters(object, ...)family_parameters(object, ...)
object |
A fitted mgcv model, an existing GAM wrapper, or an mgcv family object. Other fitting packages require their own specification. |
... |
Arguments reserved for methods. |
fitted_values() and fitted_samples() default to the parameters marked
returned. On the response scale these are natural distribution parameters,
which can differ from the fitting package's native response predictions.
For example, Gaussian LSS output contains standard deviation, whereas mgcv
predicts reciprocal standard deviation. GEV location is not its expectation.
link describes the native representation: for example, ziplss() uses
an identity link for log rate, while natural rate is the exponential of
that predictor.
The sinh-arcsinh skewness and tailweight parameters control distribution
shape; they are not the response's standardized skewness and kurtosis.
link() and inv_link() retain the fitting package's native conventions
and their existing aliases. Use the definitions here to interpret them.
A tibble with parameter, symbol, definition, native,
predictor, source, link, component, returned, and uncertainty.
Predictor indices follow the fitting package's equation order. Global
parameters have no predictor and are omitted from fitted parameter output;
they remain fixed during coefficient sampling. Derived rows identify
constraints such as a multinomial reference category. The package and
family attributes identify the parameterisation provider. The
parameterisation attribute describes the mathematical distribution.
expectation_condition records conditions for a finite expected response.
fitted_values(), fitted_samples()
family_parameters(mgcv::gevlss()) family_parameters(mgcv::gaulss()) family_parameters(mgcv::ziplss())family_parameters(mgcv::gevlss()) family_parameters(mgcv::gaulss()) family_parameters(mgcv::ziplss())
Extracts the type of family in a consistent way
family_type(object, ...) ## S3 method for class 'family' family_type(object, ...) ## Default S3 method: family_type(object, ...)family_type(object, ...) ## S3 method for class 'family' family_type(object, ...) ## Default S3 method: family_type(object, ...)
object |
an R object. Currently |
... |
arguments passed to other methods. |
Provides a stats::family() method for a range of GAM objects.
## S3 method for class 'gam' family(object, ...) ## S3 method for class 'gamm' family(object, ...) ## S3 method for class 'bam' family(object, ...) ## S3 method for class 'gamm4' family(object, ...)## S3 method for class 'gam' family(object, ...) ## S3 method for class 'gamm' family(object, ...) ## S3 method for class 'bam' family(object, ...) ## S3 method for class 'gamm4' family(object, ...)
object |
a fitted model. Models fitted by |
... |
arguments passed to other methods. |
Calculate population moments at observed or supplied covariate values, with uncertainty propagated jointly through the model's distribution parameters.
fitted_moments(object, ...) ## S3 method for class 'gam' fitted_moments( object, data = NULL, moments = c("mean", "variance", "cv"), uncertainty = c("delta", "simulation", "none"), ci_level = 0.95, unconditional = FALSE, nuisance = c("estimated", "fixed"), n_draws = 10000L, seed = NULL, scores = NULL, method = c("gaussian", "mh", "inla", "user"), draws = NULL, envir = NULL, family_index = NULL, ... )fitted_moments(object, ...) ## S3 method for class 'gam' fitted_moments( object, data = NULL, moments = c("mean", "variance", "cv"), uncertainty = c("delta", "simulation", "none"), ci_level = 0.95, unconditional = FALSE, nuisance = c("estimated", "fixed"), n_draws = 10000L, seed = NULL, scores = NULL, method = c("gaussian", "mh", "inla", "user"), draws = NULL, envir = NULL, family_index = NULL, ... )
object |
A fitted |
... |
Prediction arguments passed to |
data |
Optional prediction data. With |
moments |
Character vector selecting |
uncertainty |
One of |
ci_level |
Coverage of pointwise uncertainty intervals, between 0 and 1. |
unconditional |
Include smoothing parameter uncertainty when available. |
nuisance |
One of |
n_draws |
Number of joint parameter draws for simulation, at least two. User-supplied coefficient draws determine their own count when omitted. |
seed |
Optional integer random seed. An explicit seed preserves the
caller's random-number state; |
scores |
Optional numeric category scores, in category order, for ordinal or multinomial models. Otherwise return moments of each category's zero/one membership indicator. Binomial moments describe a Bernoulli response, independently of fitting trial counts or likelihood weights. |
method |
Coefficient sampler for simulation; see |
draws |
Optional coefficient matrix for |
envir |
Environment used to recover model covariates. |
family_index |
Optional integer component-family positions for grouped
predictions, one per supplied row. Membership is otherwise recovered as in
|
Estimates describe one response at each covariate combination, with unit
observation weight. Fitting weights are not transferred to new responses.
For ML/REML fits with an estimated dispersion, all uncertainty modes use
the likelihood estimate stored in reml.scale. The conditional coefficient
covariance is rescaled to this value. This can differ from mgcv's separate
Pearson/Fletcher estimate in sig2; the saved outer Hessian describes the
likelihood estimate, so combining it with sig2 would mix estimators.
Response variance and uncertainty in its estimate are different quantities:
.fitted contains the variance when .parameter is "variance", and .se
describes uncertainty in that estimate. These are not moments of a posterior
predictive mixture or prediction intervals for future observations.
Standard Gaussian, Poisson, binomial, Gamma and inverse-Gaussian families,
negative binomial, beta, scaled t, Tweedie, all seven location/scale/shape
families, ordinal, multinomial and multivariate-normal models are supported.
Censored normal, logistic and Poisson families return moments of the latent
uncensored response. Beta moments describe the beta likelihood, without the
epsilon clipping used by some response generators. bcg() supports the
original lognormal response only when its Box-Cox parameter is fixed at zero:
other powers require a distribution outside the inverse transformation's
domain that the fitted family does not specify. Quasi and Cox families are
unsupported. Grouped (gfam) predictions use each row's component family
and the full joint model covariance. Grouped ordinal components require
explicit category scores; grouped category-indicator output is unsupported.
The delta method differentiates the complete parameter-to-moment
transformation and uses its full joint covariance. Gaussian, Poisson, Gamma,
inverse-Gaussian and Tweedie derivatives (including their models with several predictors) are
analytic; other families use central numerical differences. Positive variance, SD, CV
and kurtosis intervals are calculated on a log scale; .se always remains
on the reported quantity's scale. Other delta intervals use the identity
scale. Simulation uses joint parameter draws and equal-tailed quantiles.
Both methods retain the moment evaluated at fitted parameters as .fitted.
With estimated global family parameters, a first-order joint Gaussian
approximation combines the conditional Bayesian coefficient covariance with
second derivatives of the ML/REML fitting criterion and derivatives of the
fitted coefficients with respect to the family and smoothing parameters. Without
unconditional, outer curvature is conditioned on smoothing parameters.
With unconditional, the full saved outer Hessian is inverted, including
its smoothing uncertainty. The curvature and coefficient sensitivities are
evaluated at the fitted parameters, with mgcv's mapping for linked or fixed
smoothing parameters. A positive-definite Hessian is required. This does not
also add the corrected coefficient
covariance, which would count that uncertainty twice. The fitted object must
store a matching Hessian and sensitivities; unsupported fitting methods,
including fast REML BAM fits, give an error. This is a local approximation
about the fitted parameters, not an exact posterior sampler for dispersion
or family shape. With fixed global parameters, the existing coefficient
covariance or post_draws() machinery is used. Delta intervals and Gaussian
simulation with unconditional = TRUE and fixed estimated global parameters use
the first-order smoothing correction conditional on those fixed parameters:
native corrected covariance can also include their uncertainty. This requires
the same saved outer Hessian and sensitivities when smoothing parameters are
present. Legacy negbin() fits outside ML/REML require explicit
nuisance = "fixed"; use nb() to estimate and propagate shape uncertainty.
The covariance calculation uses a first-order expansion of the coefficient
means and does not include mgcv's additional correction for changes in the
conditional coefficient covariance. The moment_info attribute
records which approximation was used.
Nonexistent moments are retained as NA with a status and one warning per
call. In simulation, .p_defined records the fraction of draws with a finite
value. Intervals and standard errors are withheld if any draw is undefined;
draws are never silently dropped. CV requires a positive mean, and skewness
and kurtosis require positive variance. GEV moments of order r require
shape < 1/r; t moments require degrees of freedom greater than their order.
Status values distinguish "moment_does_not_exist", "nonpositive_mean",
"zero_variance", "undefined_in_draws", and "missing_predictors".
"numerical_failure" identifies a value that could not be calculated with
finite precision or invalid distribution parameters; "derivative_unavailable"
identifies a finite estimate whose local derivative could not be calculated.
A tibble of class "fitted_moments", containing .row, covariates,
.parameter, .fitted, .se, .lower_ci, .upper_ci and .status.
Category indicators include .category; multivariate responses include
.y; grouped responses include .family. Simulation also includes .p_defined. All estimates, standard errors
and interval bounds are on the requested quantity's scale.
conditional_moments(), fitted_values(), fitted_samples()
load_mgcv() m <- gam(mpg ~ s(wt, k = 5), data = mtcars, method = "REML") fitted_moments(m, data = mtcars[1:3, ], moments = c("mean", "variance")) fitted_moments(m, data = mtcars[1:3, ], moments = "variance", uncertainty = "simulation", n_draws = 500, seed = 42)load_mgcv() m <- gam(mpg ~ s(wt, k = 5), data = mtcars, method = "REML") fitted_moments(m, data = mtcars[1:3, ], moments = c("mean", "variance")) fitted_moments(m, data = mtcars[1:3, ], moments = "variance", uncertainty = "simulation", n_draws = 500, seed = 42)
Distribution parameters or expected responses drawn from the posterior distribution of a fitted model.
## S3 method for class 'gamm4' fitted_samples(model, ...) fitted_samples(model, ...) ## S3 method for class 'gam' fitted_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, scale = c("response", "linear_predictor"), family_index = NULL, quantity = c("parameters", "expectation"), marginalise = NULL, integration = c("quadrature", "monte_carlo"), n_quad = 40L, n_integrate = 5000L ) ## S3 method for class 'scam' fitted_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, scale = c("response", "linear_predictor"), quantity = c("parameters", "expectation") )## S3 method for class 'gamm4' fitted_samples(model, ...) fitted_samples(model, ...) ## S3 method for class 'gam' fitted_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, scale = c("response", "linear_predictor"), family_index = NULL, quantity = c("parameters", "expectation"), marginalise = NULL, integration = c("quadrature", "monte_carlo"), n_quad = 40L, n_integrate = 5000L ) ## S3 method for class 'scam' fitted_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, scale = c("response", "linear_predictor"), quantity = c("parameters", "expectation") )
model |
a fitted model of the supported types; see diagnostic_support. |
... |
arguments passed to other methods. For |
data |
data frame; new observations at which the posterior draws
from the model should be evaluated. If not supplied, the data used to fit
the model will be used for |
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
chains |
positive integer or |
seed |
numeric; a random seed for the simulations. |
method |
character; which method should be used to draw samples from
the posterior distribution. |
n_cores |
positive integer; maximum concurrent MH chains using mirai,
capped at |
n_threads |
positive integer; threads within Gaussian sampling using mvnfast. Defaults to one. This is separate from concurrent MH chains. |
burnin |
numeric; number of samples to discard as the burnin draws.
Only used with |
thin |
positive integer; retain every |
t_df |
numeric; degrees of freedom for t distribution proposals. Only
used with |
rw_scale |
numeric; Factor by which to scale posterior covariance
matrix when generating random walk proposals. Negative or non finite to
skip the random walk step. Only used with |
frequentist |
logical; |
unconditional |
logical; if |
draws |
matrix; user supplied posterior draws to be used when
|
diagnostics |
logical; calculate coefficient R-hat, effective sample sizes, and Monte Carlo standard errors using the optional posterior package. |
mh_backend |
character; |
mvn_method |
character; one of |
block_size |
positive integer; maximum observation rows per block in the gratia MH evaluator. Large designs are evaluated without storing a full matrix. |
dense_limit |
numeric; maximum number of design-matrix elements to cache for the gratia MH backend. Use zero to force blockwise evaluation. |
scale |
character; |
family_index |
numeric; optional family-list positions for grouped
family ( |
quantity |
character; |
marginalise |
|
integration |
Integration method when |
n_quad |
Initial Gauss-Hermite point count, between 2 and 1000.
Successive doubled orders, up to four times this count, and an interlaced
rule with one fewer point must agree within
|
n_integrate |
Number of Monte Carlo integration draws, at least two.
These are shared across rows and posterior coefficient draws. This count
is separate from |
With marginalise, fitted samples contain posterior draws of the integrated
mean, rather than the variation among new groups. Selected fitted effects
are removed before integration. exclude cannot name a selected term and
terms is unsupported. Only response-scale means and links defined over
the whole Gaussian predictor distribution are supported. Grouping columns
can be omitted if they occur exclusively in the selected terms. A factor
also used as a selected smooth's by variable must still be supplied with
a fitted level, because it selects the relevant curve distribution. Fits
using min.sp are unsupported; see random_effect_samples().
The integration_info attribute records fixed variance estimates, the
integration method, point or draw counts, and numerical error estimates.
For Monte Carlo these errors are standard errors of integration, separate
from uncertainty in model predictions. unconditional can adjust the
coefficient covariance; it does not draw random-effect variance parameters.
Parameter names and definitions are available through family_parameters().
Gaussian LSS returns mean and sd, GEV returns location, scale and
shape, and sinh-arcsinh returns location, scale, skewness and
tailweight. These shape parameters are not response moments. Natural
parameters can differ from native mgcv predictions and inv_link() values.
Every parameter in one draw uses the same joint coefficient draw. Global
parameters outside the coefficient vector remain fixed and are described
in the metadata, rather than returned as fitted parameters.
Use quantity = "expectation" for expected responses labelled
"expectation". This includes Gumbel, GEV and sinh-arcsinh mean adjustments
and the zero-truncated Poisson adjustment in ziplss(). A GEV expectation
does not exist at shape >= 1; parameter and response draws remain available.
Categorical expectations are category probabilities, not numeric category
scores. .category identifies categories, and .y identifies multivariate
responses. Multinomial link output includes a zero reference predictor.
Ordinal parameter output is the latent location predictor; its thresholds
are global parameters.
The prediction_info attribute records the quantity, scale and resolved
parameter descriptions. Unlike posterior_samples(), these draws add no
response noise. predicted_samples() instead simulates observations with
coefficients held at their fitted values.
For grouped families, coefficient draws preserve the joint model covariance;
each row is then transformed using its own fitted component family. Explicit
prediction data must identify each row's family: no training-order fallback
is used. A two-column response matrix supplies its second column; a numeric
column named for the response supplies indices directly. For a response such
as cbind(y, index), the index expression can be supplied without y.
Missing indices behave like missing required predictors. Link-scale draws
do not require family membership.
Grouped parameter output includes the latent location for ordinal components.
Grouped expectations include scalar fitted means and ordinal category
probabilities, with .category identifying the ordinal category and NA
for scalar components. Distributional nuisance parameters are held at
their fitted values. This does not add support for general/location-scale
families that gfam() itself rejects, nor repair upstream fitting failures
(including fixed-theta negative-binomial components and some ziP() fits
in some mgcv versions).
Observation rows use the same missing-value convention as
posterior_samples(): default results restore na.exclude observations in
every draw, while explicit data are evaluated in their own row order.
A tibble (data frame) in long format, with columns:
.row: row of the evaluation data;
.draw: globally unique draw identifier;
.parameter: the distribution parameter name, or "expectation";
.fitted: the parameter, predictor or expected response requested.
Multiple-chain output also includes .chain and .iteration. Attached
coefficient diagnostics are available through sampling_diagnostics().
With data = NULL, fitting offsets are retained, including offsets
supplied through the fitting function's offset argument. Explicit prediction
data follow mgcv::predict.gam(): offsets in formulas are evaluated from
the prediction data, while offsets supplied through the fitting function's
offset argument are not transferred to new observations. Include offsets
in the formula when predicting at new data; the required offset variables
must then be present in data.
Gavin L. Simpson
Wood, S.N., (2020). Simplified integrated nested Laplace approximation. Biometrika 107, 223–230. doi:10.1093/biomet/asz044
load_mgcv() dat <- data_sim("eg1", n = 1000, dist = "normal", scale = 2, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") fs <- fitted_samples(m1, n_draws = 5, seed = 42) fs # can generate own set of draws and use them drws <- generate_draws(m1, n_draws = 2, seed = 24) fs2 <- fitted_samples(m1, method = "user", draws = drws) fs2load_mgcv() dat <- data_sim("eg1", n = 1000, dist = "normal", scale = 2, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") fs <- fitted_samples(m1, n_draws = 5, seed = 42) fs # can generate own set of draws and use them drws <- generate_draws(m1, n_draws = 2, seed = 24) fs2 <- fitted_samples(m1, method = "user", draws = drws) fs2
Generate fitted values from a estimated GAM
fitted_values(object, ...) ## S3 method for class 'gam' fitted_values( object, data = NULL, scale = c("response", "link", "linear predictor"), ci_level = 0.95, envir = NULL, ..., interval = c("confidence", "simultaneous"), n_sim = 10000, n_cores = 1, seed = NULL, unconditional = FALSE, interval_method = c("auto", "gaussian", "bootstrap"), quantity = c("parameters", "expectation"), family_index = NULL, marginalise = NULL, integration = c("quadrature", "monte_carlo"), n_quad = 40L, n_integrate = 5000L ) ## S3 method for class 'gamm' fitted_values(object, ...) ## S3 method for class 'scam' fitted_values(object, ..., unconditional = FALSE) ## S3 method for class 'gamm4' fitted_values(object, ...)fitted_values(object, ...) ## S3 method for class 'gam' fitted_values( object, data = NULL, scale = c("response", "link", "linear predictor"), ci_level = 0.95, envir = NULL, ..., interval = c("confidence", "simultaneous"), n_sim = 10000, n_cores = 1, seed = NULL, unconditional = FALSE, interval_method = c("auto", "gaussian", "bootstrap"), quantity = c("parameters", "expectation"), family_index = NULL, marginalise = NULL, integration = c("quadrature", "monte_carlo"), n_quad = 40L, n_integrate = 5000L ) ## S3 method for class 'gamm' fitted_values(object, ...) ## S3 method for class 'scam' fitted_values(object, ..., unconditional = FALSE) ## S3 method for class 'gamm4' fitted_values(object, ...)
object |
a fitted model. Currently only models fitted by |
... |
arguments passed to |
data |
optional data frame of covariate values for which fitted values are to be returned. |
scale |
character; what scale should the fitted values be returned on?
|
ci_level |
numeric; a value between 0 and 1 indicating the coverage of the credible interval. |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
interval |
character; |
n_sim |
positive integer; number of coefficient draws used for simultaneous intervals. Ignored for pointwise intervals. |
n_cores |
positive integer; number of cores used by |
seed |
integer or |
unconditional |
logical; include smoothing parameter uncertainty in the Bayesian covariance matrix, if available. Otherwise a warning is issued and the uncorrected covariance is used. |
interval_method |
character; |
quantity |
character; |
family_index |
numeric; optional family-list positions for grouped
family ( |
marginalise |
|
integration |
Integration method when |
n_quad |
Initial Gauss-Hermite point count, between 2 and 1000.
Successive doubled orders, up to four times this count, and an interlaced
rule with one fewer point must agree within
|
n_integrate |
Number of Monte Carlo integration draws, at least two.
These are shared across rows and posterior coefficient draws. This count
is separate from |
With marginalise, predictions are response means averaged over the selected
random-effect distributions, using the methods described in fitted_samples().
The point estimate uses fitted coefficients; pointwise intervals use the
derivative of the integrated mean and the coefficient covariance. .se is
on the response scale. These normal intervals are not clipped to the response
range. Simultaneous and bootstrap marginal intervals are not yet supported.
The integration_info attribute records numerical accuracy and fixed
variance estimates.
quantity = "parameters" returns all distribution parameters represented
by predictors, including intercept-only predictors. See family_parameters()
for their definitions. These are natural distribution parameters, which
can differ from mgcv's native response predictions: Gaussian LSS returns
standard deviation, GEV returns location rather than expectation, and
sinh-arcsinh returns shape parameters rather than response moments.
quantity = "expectation" returns the expected response on the response
scale, labelled "expectation". Categorical expectations are probabilities
of category membership; multivariate models return a mean per response.
.category and .y identify the category or response separately from
.parameter. Global parameters are described but held fixed when calculating
coefficient uncertainty. Coupled expectations use the full coefficient
covariance and a delta-method Jacobian. Their intervals are pointwise.
Ordinal and multinomial probability intervals use a normal approximation to
log odds, transformed back to probabilities. Log odds and their uncertainty
are computed before rounding probabilities, so valid probabilities rounded
to zero or one retain defined intervals.
The prediction_info attribute records the quantity, scale, standard-error
scale and parameter descriptions. Parameter standard errors retain their
link-scale meaning; category-probability and expectation standard errors are
on the response scale. Unsupported simultaneous or bootstrap transformations
are rejected rather than combining marginal parameter intervals.
Native scasm fits with stored bootstrap draws use mgcv's pointwise limits
by default, including its svar.only correction for smoothing bias.
interval_method = "gaussian" restores covariance-based limits. .se
retains its existing covariance-based meaning. No replicates are generated.
Bootstrap limits use existing scalar and location-scale parameter
transformations. Unsupported nonlinear family outputs give an error for
an explicit bootstrap request; automatic selection warns and uses Gaussian
limits. Simultaneous bootstrap bands are not supported. Automatic
simultaneous intervals warn when stored bootstrap draws are left unused.
The interval_info attribute records the method and correction.
Formula offsets are included in predictions. Offsets supplied only through
the fitting function's offset argument are omitted, including when
data = NULL: this function evaluates explicit prediction rows internally.
In contrast, fitted_samples() retains fitting-argument offsets when its
data argument is NULL. Put offsets in the formula to evaluate them at
new observations.
With data = NULL, results follow the model's na.action: na.exclude
restores excluded observations as NA fitted values, standard errors and
interval bounds; na.omit returns only retained observations. Covariates
unavailable in the stored model frame are restored as typed NA values.
.row indexes the fitting data after any subset was applied.
Supplying data requests predictions at those rows, independently of training
exclusions. Missing responses do not prevent prediction. Missing required
predictors produce NA results by default. An explicit na.action passed
through ... is honoured; with na.omit, .row retains the positions in the
supplied data, rather than numbering the remaining rows consecutively.
For supplied prediction data, an informative message identifies combinations of categorical predictor levels absent from the retained fitting observations. Predictions are unchanged: an unobserved combination is not necessarily non-estimable, particularly in additive models. Numeric-by-factor range extrapolation is not checked. Missing predictors and genuinely new factor levels retain their usual prediction behavior.
Simultaneous intervals jointly cover the model's underlying expected
responses, or linear predictors on the link scale, at all valid covariate
combinations evaluated in this call, with approximate posterior probability
ci_level. The fitted values are estimates of these quantities. The
combinations may include factor levels and need not form an ordered sequence,
curve, or grid. This interpretation also applies to two predictions.
With data = NULL, the simultaneous set comprises the retained fitting
covariate combinations. Missing predictions do not enter this set. Coverage
is not asserted outside this set or between its points. Separate calls
define separate simultaneous sets. These are uncertainty intervals for model
predictions, not prediction intervals for future observations.
Simultaneous intervals use joint Gaussian coefficient draws and a critical
value based on the maximum absolute standardized deviation over the supplied
rows. Their limits are computed on the link scale and transformed if
scale = "response"; .se remains on the link scale. The simulation
covariance may be positive semidefinite. Supported families are Gaussian,
Poisson, binomial, Gamma, inverse Gaussian, quasi families, negative binomial,
Tweedie, beta regression, and scaled t, fitted by gam() or bam() (including
the gam component of a gamm() fit), and by scam(). For SCAM models,
the Gaussian approximation uses transformed coefficients conditional on
the fitted smoothing parameters. Other families support pointwise intervals
only.
Response-scale simultaneous intervals support the identity, log, logit,
probit, cloglog, cauchit, square-root, inverse, and inverse-squared links.
Intervals crossing an inverse-link domain boundary are rejected; use
scale = "link" for these intervals or for other links.
terms and exclude in ... retain mgcv::predict.gam() semantics and
apply to both prediction and interval calculation. If terms are selected or
excluded, intervals concern that selected quantity, not necessarily the full
expected response. Use the link scale for sums of smooth contributions, and
consider the intercept and offset treatment when selecting terms.
A tibble (data frame) whose first m columns contain either the data
used to fit the model (if data was NULL), or the variables supplied to
data. The result also includes:
.parameter: parameter name, or "expectation",
.fitted: the requested quantity on the specified scale,
.se: standard error; see prediction_info for its scale,
.lower_ci, .upper_ci: the limits of the credible interval on the fitted values,
on the specified scale.
Models fitted with certain families will include additional variables
mgcv::ocat() models: when quantity = "expectation", the returned object will
contain a .row column and a .category column, which indicate to which row
of the data each row of the returned object belongs. Additionally, there
will be nrow(data) * n_categories rows in the returned object; each row
is the predicted probability for a single category of the response.
For parameter output, the .se component is on the link
(linear predictor) scale. Multinomial probabilities on the response scale
and all expected responses have response-scale standard errors.
load_mgcv() sim_df <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = sim_df, method = "REML") fv <- fitted_values(m) fv # Simultaneous intervals for two arbitrary covariate combinations fitted_values(m, data = sim_df[c(1, 20), ], interval = "simultaneous", n_sim = 1000, seed = 42) # A selected sum of smooth contributions on the link scale fitted_values(m, data = sim_df[c(1, 20), ], scale = "link", terms = c("s(x2)", "s(x3)"), interval = "simultaneous", n_sim = 1000, seed = 42)load_mgcv() sim_df <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = sim_df, method = "REML") fv <- fitted_values(m) fv # Simultaneous intervals for two arbitrary covariate combinations fitted_values(m, data = sim_df[c(1, 20), ], interval = "simultaneous", n_sim = 1000, seed = 42) # A selected sum of smooth contributions on the link scale fitted_values(m, data = sim_df[c(1, 20), ], scale = "link", terms = c("s(x2)", "s(x3)"), interval = "simultaneous", n_sim = 1000, seed = 42)
Removes evaluated offset columns while retaining their raw input variables.
Raw inputs are recovered from fitting data if needed; transformed offset
values are never renamed as raw values. A scalar offset_val overrides the
raw input only for a single offset with one unambiguous input variable.
fix_offset(model, newdata, offset_val = NULL)fix_offset(model, newdata, offset_val = NULL)
model |
a fitted GAM. |
newdata |
data frame; new values at which to predict at. |
offset_val |
numeric, optional; if provided, then the offset variable
in |
The original newdata is returned with fixed names and possibly
modified offset variable.
Gavin L. Simpson
load_mgcv() df <- data_sim("eg1", n = 400, dist = "normal", seed = 2) m <- gam(y ~ s(x0) + s(x1) + offset(x2), data = df, method = "REML") names(model.frame(m)) names(fix_offset(m, model.frame(m), offset_val = 1L))load_mgcv() df <- data_sim("eg1", n = 400, dist = "normal", seed = 2) m <- gam(y ~ s(x0) + s(x1) + offset(x2), data = df, method = "REML") names(model.frame(m)) names(fix_offset(m, model.frame(m), offset_val = 1L))
Extract fixed effects estimates from a fitted model
fixed_effects(object, ...) ## S3 method for class 'gam' fixed_effects(object, ...) ## S3 method for class 'gamm' fixed_effects(object, ...) ## S3 method for class 'gamm4' fixed_effects(object, ...) ## S3 method for class 'lm' fixed_effects(object, ...) ## S3 method for class 'glm' fixed_effects(object, ...) ## Default S3 method: fixed_effects(object, ...) ## S3 method for class 'scam' fixed_effects(object, ...)fixed_effects(object, ...) ## S3 method for class 'gam' fixed_effects(object, ...) ## S3 method for class 'gamm' fixed_effects(object, ...) ## S3 method for class 'gamm4' fixed_effects(object, ...) ## S3 method for class 'lm' fixed_effects(object, ...) ## S3 method for class 'glm' fixed_effects(object, ...) ## Default S3 method: fixed_effects(object, ...) ## S3 method for class 'scam' fixed_effects(object, ...)
object |
a fitted model. Supported classes are models fitted by
|
... |
arguments passed to other methods |
load_mgcv() # run example if lme4 is available if (require("lme4")) { data(sleepstudy, package = "lme4") m <- gam( Reaction ~ Days + s(Subject, bs = "re") + s(Days, Subject, bs = "re"), data = sleepstudy, method = "REML" ) fixed_effects(m) }load_mgcv() # run example if lme4 is available if (require("lme4")) { data(sleepstudy, package = "lme4") m <- gam( Reaction ~ Days + s(Subject, bs = "re") + s(Days, Subject, bs = "re"), data = sleepstudy, method = "REML" ) fixed_effects(m) }
Models fitted by gamm4::gamm4() (version 0.2-7 or later) have class
"gamm4". Pass the fitted object directly to gratia methods; historical
unclassed lists are not supported.
Smooths, parametric effects, predictions, derivatives, simulations,
and posterior draws describe the population GAM component. Terms supplied
through random are excluded, including their realized effects, predictive
variation, and uncertainty. conditional_values() and
conditional_differences() condition on covariate values, not on realized
group effects. Group variables occurring only in random are not required
in prediction data, so new groups receive the same population predictions.
Use the mer component with lme4 for predictions conditional on group
effects and simulations including their variation. Diagnostics and response
simulations use the full fitted mixed model by default. With
conditioning = "conditional", all fitted smooth and additional random
effects are held fixed for response references. "marginal" draws new effects
from their fitted distribution. "gam_component" explicitly selects the
extracted GAM calculations used by earlier versions.
Marginal GLMM checks average over random effects using lme4's joint response
simulations. Residuals then use ranks in a shared reference sample, as
described in diagnostic_support. Gaussian identity-link models instead
use analytic CDFs of the marginal response distribution.
Posterior response draws also default to the full conditional model. They
draw fixed and fitted random effects together, keeping covariance parameters
at their fitted values. These Gaussian approximations currently use fitting
observations only. To supply user coefficient draws or prediction data to
posterior_samples(), select conditioning = "gam_component" explicitly.
Coefficient draws from post_draws(), fitted_samples(), predicted_samples()
and smooth_samples() still use the fitted GAM covariance matrix, including
its uncertainty due to fitting the mixed model. User draws must have one
column per GAM coefficient. Metropolis-Hastings sampling is unsupported:
the GAM likelihood does not include the additional random effects.
Smoothness uncertainty-corrected covariance matrices and alternative EDF
are unavailable from gamm4; requested corrections warn and fall back to
the available covariance matrix or EDF. Variance components are extracted
from the mixed-model component. Smooth components use the same penalty
scale and labels as gam() and bam(), with a separate row for each
penalty of a tensor or factor smooth. Additional random effects retain
their mixed-model variances. Confidence intervals use likelihood profiles
by default; use interval_method = "none" to obtain estimates only.
Gaussian profiles use a maximum-likelihood refit even when the reported
estimates were fitted by REML. See variance_comp for interval details.
With type = "terms", variances describe fitted term contributions,
including the additional random effects. Their covariance matrix is
returned in the covariance attribute. Term intervals use joint posterior
coefficient draws, retaining covariance with the additional fitted random
effects. Use n_draws = 0 for term estimates without intervals.
Posterior samples using a Gaussian approximation
## S3 method for class 'gamm4' gaussian_draws(model, ...) gaussian_draws(model, ...) ## S3 method for class 'gam' gaussian_draws( model, ..., n_draws = NULL, n_threads = 1L, frequentist = FALSE, unconditional = FALSE, mvn_method = "mvnfast", index = NULL, seed = NULL, chains = NULL, diagnostics = FALSE ) ## S3 method for class 'scam' gaussian_draws( model, ..., n_draws = NULL, n_threads = 1L, frequentist = FALSE, unconditional = FALSE, mvn_method = "mvnfast", index = NULL, parametrized = TRUE, seed = NULL, chains = NULL, diagnostics = FALSE )## S3 method for class 'gamm4' gaussian_draws(model, ...) gaussian_draws(model, ...) ## S3 method for class 'gam' gaussian_draws( model, ..., n_draws = NULL, n_threads = 1L, frequentist = FALSE, unconditional = FALSE, mvn_method = "mvnfast", index = NULL, seed = NULL, chains = NULL, diagnostics = FALSE ) ## S3 method for class 'scam' gaussian_draws( model, ..., n_draws = NULL, n_threads = 1L, frequentist = FALSE, unconditional = FALSE, mvn_method = "mvnfast", index = NULL, parametrized = TRUE, seed = NULL, chains = NULL, diagnostics = FALSE )
model |
a fitted model from |
... |
arguments passed to methods. |
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
n_threads |
positive integer; threads within Gaussian sampling using mvnfast. Defaults to one. This is separate from concurrent MH chains. |
frequentist |
logical; if |
unconditional |
logical; if |
mvn_method |
character; one of |
index |
numeric; vector of indices of coefficients to use. Can be used
to subset the mean vector and covariance matrix extracted from |
seed |
numeric or |
chains |
positive integer or |
diagnostics |
logical; calculate coefficient R-hat, effective sample sizes, and Monte Carlo standard errors using the optional posterior package. |
parametrized |
logical; for SCAM fits, transform Gaussian draws from
the unrestricted fitting coefficients using the fitted positivity transform.
This preserves the smooth's constraints. With |
Sampling controls must be named. Removed arguments produce migration errors;
see vignette("sampling-migration"). Explicit controls that the selected
method cannot use are rejected.
For SCAM models, Gaussian draws approximate the distribution of the unrestricted
fitting coefficients using Vp (or Ve with frequentist = TRUE), then apply
scam's fitted exponential or notExp transformation. This is an approximation
in fitting coordinates, rather than an exact constrained posterior. Supplied
draws must already use the transformed coordinates in coef(model) order.
Numerically singular covariance matrices are sampled by eigen decomposition;
negative eigenvalues within 100 * .Machine$double.eps * ncol(V) times the
largest absolute eigenvalue are treated as zero. Larger negatives are errors.
For weakly identified exponential coefficients, a very large fitting-coordinate
variance can yield non-finite transformed draws. Sampling then reports an
error because this Gaussian approximation cannot provide usable draws; supply
finite transformed draws from a suitable alternative sampler.
For multiple chains, n_draws is the total retained count and must be divisible
by chains. Coefficient matrices carry a chain mapping; use
as_mcmc_draws() before ordinary matrix operations remove that mapping.
Higher-level sampling tables include .chain and .iteration for multiple
chains, with .draw unique across chains. Default single-chain table columns
are unchanged. Use sampling_diagnostics() to extract coefficient diagnostics
before response simulation adds further noise.
The gratia MH backend supports Gaussian identity, Poisson log, binomial
logit, Gamma log, and negative binomial log fits. It evaluates the fitted
bases at original covariates, including for discrete bam fits. GAMM components, AR1 dependence,
paraPen, H, and fits made from pre-fit G objects are unsupported.
The family MH backend calls the fitted family's dev.resids() and linkinv()
functions, or ll() for families with multiple linear predictors. This
retains response encodings and attributes such as censoring indicators and
the mappings between coefficients and predictors. It supports compatible
standard, extended, and general mgcv families, including multinomial, Gaussian
location-scale, and grouped families. Quasi families, Cox proportional hazards
models, GAMM components, AR1 dependence, paraPen, H, and pre-fit G objects
are unsupported. The fitted coefficient covariance must be nonsingular.
It always caches the full design matrix; block_size and dense_limit apply
only to the gratia backend and are rejected for the family backend.
The new MH backends reject bam fits with nonzero prescribed smooth
contributions: mgcv fitting and prediction can use different offsets for
those fits. Supplied coefficient draws can still be evaluated with the
native prediction conventions.
All MH backends sample the conditional coefficient posterior with fitted
smoothing, dispersion, and additional family parameters fixed. Parameters
represented in the fitted coefficient vector are sampled, including scale
or covariance coefficients in general families. unconditional applies
to Gaussian draws only.
GAM-class fits with linear inequality constraints, including
mgcv::scasm() fits, store these as Ain %*% coefficients >= bin.
Gaussian sampling uses the fitted covariance matrix without enforcing
these inequalities and issues a warning. Sampled smooths can therefore
violate the fitted shape constraints. Pointwise intervals computed from
the same Gaussian covariance approximation also need not preserve those
shapes. All MH backends are unavailable for these fits because
the samplers do not enforce their inequalities.
If mgcv::scasm() was fitted with bs > 0, its bs component stores
coefficient draws from the native constrained bootstrap in columns. These
can be supplied explicitly as draws = t(model$bs) with method = "user".
The result then describes bootstrap variation, rather than Gaussian
posterior sampling. Gratia does not automatically select these draws.
The caller is responsible for the interpretation and constraint
feasibility of user-supplied draws.
Extract an factor-by smooth by name
get_by_smooth(object, term, level)get_by_smooth(object, term, level)
object |
a fitted GAM model object. |
term |
character; the name of a smooth term to extract. |
level |
character; which level of the factor to extract the smooth for. |
A single smooth object, or a list of smooths if several match the named term.
Extract an mgcv smooth by name
get_smooth(object, term)get_smooth(object, term)
object |
a fitted GAM model object. |
term |
character; the exact name of a smooth term to extract |
A single smooth object, or a list of smooths if several match the named term.
Extract an mgcv smooth given its position in the model object
get_smooths_by_id(object, id, ...) ## S3 method for class 'gam' get_smooths_by_id(object, id, ...) ## S3 method for class 'scam' get_smooths_by_id(object, id, ...) ## S3 method for class 'gamm' get_smooths_by_id(object, id, ...) ## S3 method for class 'gamm4' get_smooths_by_id(object, id, ...)get_smooths_by_id(object, id, ...) ## S3 method for class 'gam' get_smooths_by_id(object, id, ...) ## S3 method for class 'scam' get_smooths_by_id(object, id, ...) ## S3 method for class 'gamm' get_smooths_by_id(object, id, ...) ## S3 method for class 'gamm4' get_smooths_by_id(object, id, ...)
object |
a fitted GAM model object. |
id |
numeric; the position of the smooth in the model object. |
... |
Arguments passed to methods. |
Extract the covariance matrix of the model parameters or a subset of these for a particular model term
get_vcov( object, unconditional = FALSE, frequentist = FALSE, term = NULL, by_level = NULL ) ## S3 method for class 'scam' get_vcov( object, unconditional = FALSE, frequentist = FALSE, term = NULL, by_level = NULL )get_vcov( object, unconditional = FALSE, frequentist = FALSE, term = NULL, by_level = NULL ) ## S3 method for class 'scam' get_vcov( object, unconditional = FALSE, frequentist = FALSE, term = NULL, by_level = NULL )
object |
an R object from which a covariance matrix shall be extracted. |
unconditional |
logical; if |
frequentist |
logical; if |
term |
character, length 1; return the subset of the covariance matrix for a particular smooth term. Only a single term can be selected. |
by_level |
character; currently unsued. |
For mgcv::scasm() fits with linear inequality constraints,
the Gaussian covariance approximation does not enforce the fitted shapes.
Pointwise intervals calculated from this matrix can extend outside those
constraints. See post_draws() for sampling and native-bootstrap details.
a matrix containing the selected covariance matrix.
Gavin L. Simpson
Create a palette function for ggplot2 theme settings. The default preserves gratia's existing nine-colour Okabe-Ito palette and hue fallback.
gratia_palette(name = "default", reverse = FALSE)gratia_palette(name = "default", reverse = FALSE)
name |
Palette name: |
reverse |
Logical; reverse the palette order? |
Tol's bright and vibrant palettes contain seven colours, muted contains nine, and dark contains eleven. The dark palette favours visibility against white over separation between colours. Banded palettes provide 12, 16 or 20 colours; neighbouring shades become less distinct as the palette grows. These are optional choices and do not change gratia's defaults.
Finite palettes use the published order, returning the first requested colours. They error if their capacity is exceeded; they never recycle or interpolate colours. The default palette uses hue colours above nine levels. Set both colour and fill palettes to keep grouped curves and ribbons paired.
Definitions follow Paul Tol's colour schemes as published in August 2026. The banded schemes are derived from his sequential schemes for use when larger sets of colours are required. See https://sronpersonalpages.nl/~pault/ for the definitions and examples.
A function taking the number of colours and returning a character vector of hexadecimal colours.
pal <- gratia_palette("tol_muted") pal(5) ggplot2::theme( palette.colour.discrete = pal, palette.fill.discrete = pal )pal <- gratia_palette("tol_muted") pal(5) ggplot2::theme( palette.colour.discrete = pal, palette.fill.discrete = pal )
Gratia plots use ordinary ggplot2 themes. Component settings are read when
the plot is built, so they can also be changed after calling draw().
gratia_theme_get() gratia_theme_set(theme = NULL) gratia_theme_update(...)gratia_theme_get() gratia_theme_set(theme = NULL) gratia_theme_update(...)
theme |
A ggplot2 theme, or |
... |
Settings passed to |
gratia_theme_get() returns the override stored in
options("gratia.plot.theme"). It does not include ggplot2's active theme.
The override is attached to each plot when it is constructed. Later changes
to this option affect new plots. Use withr::with_options() for a temporary
override. Unspecified settings inherit ggplot2's active theme as usual.
Component elements accept ggplot2::element_geom(). The main elements are
geom.gratia.smooth, geom.gratia.effect, geom.gratia.derivative,
geom.gratia.sample, geom.gratia.interval, geom.gratia.partial.residual,
geom.gratia.increase, geom.gratia.decrease, geom.gratia.change,
geom.gratia.diagnostic.point, geom.gratia.reference, geom.gratia.rug,
geom.gratia.contour, geom.gratia.boundary, geom.gratia.observed,
geom.gratia.replicated, geom.gratia.chain, geom.gratia.histogram,
geom.gratia.rootogram.bar, geom.gratia.rootogram.fitted, and
geom.gratia.concurvity.bar. Other elements are geom.gratia.curve
(the parent of smooth, effect, derivative, sample and basis),
geom.gratia.basis, geom.gratia.surface, geom.gratia.diagnostic.boxplot,
geom.gratia.residual.covariate.point, geom.gratia.diagnostic.reference,
geom.gratia.chain.reference, geom.gratia.correlation.reference,
geom.gratia.histogram.outline, geom.gratia.rootogram.reference,
geom.gratia.rootogram.warning, geom.gratia.correlation, and
geom.gratia.trend.
Opacity is set separately, using numeric elements between zero and one:
gratia.alpha.interval, gratia.alpha.partial.residual,
gratia.alpha.diagnostic.point, gratia.alpha.rug,
gratia.alpha.sample, gratia.alpha.observed,
gratia.alpha.replicated, gratia.alpha.chain,
gratia.alpha.histogram, and gratia.alpha.surface.interval.
More specific elements, such as geom.gratia.smooth.interval,
geom.gratia.diagnostic.interval, geom.gratia.surface.interval,
geom.gratia.surface.rug, and their gratia.alpha.* counterparts,
override the general component setting.
Standard fields such as colour, fill, linewidth, pointsize and
pointshape set component defaults. Fields such as ink and borderwidth
follow the parent ggplot2 geom's interpretation.
Default component settings preserve the existing plot appearance. Mapped
aesthetics retain their scales. Explicit aesthetic arguments to plotting
functions are deprecated but remain fixed overrides; use themes instead.
Palette settings use palette.colour.discrete, palette.fill.discrete,
palette.colour.continuous, and palette.fill.continuous. Complete scale
objects can still be supplied through the existing scale arguments.
For a single ggplot, add a theme with +. For a patchwork returned by
draw() or appraise(), use & to affect every panel. Plots delegated to
bayesplot retain that package's styling.
gratia_theme_get() returns a theme or NULL. The setter and updater
invisibly return the previous override.
library("ggplot2") old <- gratia_theme_set(theme( geom.gratia.smooth = element_geom(colour = "navy"), gratia.alpha.interval = 0.15 )) gratia_theme_update(geom.gratia.contour = element_geom(colour = "grey40")) gratia_theme_set(old) pal <- gratia_palette("tol_banded_16") theme(palette.colour.discrete = pal, palette.fill.discrete = pal)library("ggplot2") old <- gratia_theme_set(theme( geom.gratia.smooth = element_geom(colour = "navy"), gratia.alpha.interval = 0.15 )) gratia_theme_update(geom.gratia.contour = element_geom(colour = "grey40")) gratia_theme_set(old) pal <- gratia_palette("tol_banded_16") theme(palette.colour.discrete = pal, palette.fill.discrete = pal)
A subset of the data from the carData::GSSvocab dataset from the
carData package, containing observations from 2016 only.
A data frame with 1858 rows and 3 variables:
vocab: numeric; the number of words out of 10 correct on a vocabulary
test.
nativeBorn: factor; Was the respondent born in the US? A factor with
levels no and yes.
ageGroup: factor; grouped age of the respondent with levels 18-29
30-39, 40-49, 50-59, and 60+.
Gu and Wahba test functions
gw_f0(x, ...) gw_f1(x, ...) gw_f2(x, ...) gw_f3(x, ...)gw_f0(x, ...) gw_f1(x, ...) gw_f2(x, ...) gw_f3(x, ...)
x |
numeric; vector of points to evaluate the function at, on interval (0,1) |
... |
arguments passed to other methods, ignored. |
x <- seq(0, 1, length = 6) gw_f0(x) gw_f1(x) gw_f2(x) gw_f3(x) # should be constant 0x <- seq(0, 1, length = 6) gw_f0(x) gw_f1(x) gw_f2(x) gw_f3(x) # should be constant 0
Are additional parameters available for a GAM?
has_theta(object)has_theta(object)
object |
an R object, either a |
A logical; TRUE if additional parameters available, FALSE
otherwise.
load_mgcv() df <- data_sim("eg1", dist = "poisson", seed = 42, scale = 1 / 5) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML", family = nb() ) has_theta(m) p <- theta(m)load_mgcv() df <- data_sim("eg1", dist = "poisson", seed = 42, scale = 1 / 5) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML", family = nb() ) has_theta(m) p <- theta(m)
Functions to check if a smooth is a by-variable one and to test of the type of by-variable smooth is a factor-smooth or a continuous-smooth interaction.
is_by_smooth(smooth) is_factor_by_smooth(smooth) is_continuous_by_smooth(smooth) by_variable(smooth) by_level(smooth)is_by_smooth(smooth) is_factor_by_smooth(smooth) is_continuous_by_smooth(smooth) by_variable(smooth) by_level(smooth)
smooth |
an object of class |
A logical vector.
Gavin L. Simpson
Given the name (a term label) of a term in a model, identify if the term is a
factor term or numeric. This is useful when considering interactions, where
terms like fac1:fac2 or num1:fac1 may be requested by the user. Only for
terms of the type fac1:fac2 will this function return TRUE.
## S3 method for class 'gamm4' is_factor_term(object, term, ...) is_factor_term(object, term, ...) ## S3 method for class 'terms' is_factor_term(object, term, ...) ## S3 method for class 'gam' is_factor_term(object, term, ...) ## S3 method for class 'bam' is_factor_term(object, term, ...) ## S3 method for class 'gamm' is_factor_term(object, term, ...) ## S3 method for class 'list' is_factor_term(object, term, ...)## S3 method for class 'gamm4' is_factor_term(object, term, ...) is_factor_term(object, term, ...) ## S3 method for class 'terms' is_factor_term(object, term, ...) ## S3 method for class 'gam' is_factor_term(object, term, ...) ## S3 method for class 'bam' is_factor_term(object, term, ...) ## S3 method for class 'gamm' is_factor_term(object, term, ...) ## S3 method for class 'list' is_factor_term(object, term, ...)
object |
an R object on which method dispatch is performed |
term |
character; the name of a model term, in the sense of
|
... |
arguments passed to other methods. |
A logical: TRUE if and only if all variables involved in the term
are factors, otherwise FALSE.
Checks to determine if object is a family object of one of the three or so
types that mgcv produces.
is_mgcv_family(object)is_mgcv_family(object)
object |
the object to test. |
A logical vector of length 1, indicating if object is one of
mgcv's (TRUE), or otherwise (FALSE).
Check if objects are smooths or are a particular type of smooth
is_mgcv_smooth(smooth) stop_if_not_mgcv_smooth(smooth) check_is_mgcv_smooth(smooth) is_mrf_smooth(smooth)is_mgcv_smooth(smooth) stop_if_not_mgcv_smooth(smooth) check_is_mgcv_smooth(smooth) is_mrf_smooth(smooth)
smooth |
an R object, typically a list |
Check if a smooth inherits from class "mgcv.smooth".
stop_if_not_mgcv_smooth() is a wrapper around is_mgcv_smooth(), useful
when programming for checking if the supplied object is one of mgcv's
smooths, and throwing a consistent error if not.
check_is_mgcv_smooth() is similar to stop_if_not_mgcv_smooth() but
returns the result of is_mgcv_smooth() invisibly.
Determines whether a fitted model (GAM) is truly multivariate or not.
is_multivariate_y(model)is_multivariate_y(model)
model |
a fitted model object; currently only for |
A logical vector of length 1, indicating if model is multivariate
(TRUE), or otherwise (FALSE).
Given a character vector of model terms, checks to see which, if any, is the model offset.
is_offset(terms)is_offset(terms)
terms |
character vector of model terms. |
A logical vector of the same length as terms.
Gavin L. Simpson
load_mgcv() df <- data_sim("eg1", n = 400, dist = "normal") m <- gam(y ~ s(x0) + s(x1) + offset(x0), data = df, method = "REML") nm <- names(model.frame(m)) nm is_offset(nm)load_mgcv() df <- data_sim("eg1", n = 400, dist = "normal") m <- gam(y ~ s(x0) + s(x1) + offset(x0), data = df, method = "REML") nm <- names(model.frame(m)) nm is_offset(nm)
Returns the link or its inverse from an estimated model, and provides a simple way to extract these functions from complex models with multiple links, such as location scale models.
link(object, ...) ## S3 method for class 'family' link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'gam' link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'bam' link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'gamm' link(object, ...) ## S3 method for class 'glm' link(object, ...) ## S3 method for class 'gamm4' link(object, ...) inv_link(object, ...) ## S3 method for class 'family' inv_link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'gam' inv_link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'bam' inv_link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'gamm' inv_link(object, ...) ## S3 method for class 'gamm4' inv_link(object, ...) ## S3 method for class 'glm' inv_link(object, ...) extract_link(family, ...) ## S3 method for class 'family' extract_link(family, inverse = FALSE, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'general.family' extract_link(family, parameter = NULL, inverse = FALSE, which_eta = NULL, ...)link(object, ...) ## S3 method for class 'family' link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'gam' link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'bam' link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'gamm' link(object, ...) ## S3 method for class 'glm' link(object, ...) ## S3 method for class 'gamm4' link(object, ...) inv_link(object, ...) ## S3 method for class 'family' inv_link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'gam' inv_link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'bam' inv_link(object, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'gamm' inv_link(object, ...) ## S3 method for class 'gamm4' inv_link(object, ...) ## S3 method for class 'glm' inv_link(object, ...) extract_link(family, ...) ## S3 method for class 'family' extract_link(family, inverse = FALSE, parameter = NULL, which_eta = NULL, ...) ## S3 method for class 'general.family' extract_link(family, parameter = NULL, inverse = FALSE, which_eta = NULL, ...)
object |
a family object or a fitted model from which to extract the
family object. Models fitted by |
... |
arguments passed to other methods. |
parameter |
character; which parameter of the distribution. Usually
|
which_eta |
numeric; the integer index of the linear predictor to
extract for families |
family |
a family object, the result of a call to |
inverse |
logical; return the inverse of the link function? |
Gavin L. Simpson
load_mgcv() link(gaussian()) link(nb()) inv_link(nb()) dat <- data_sim("eg1", seed = 4234) mod <- gam(list(y ~ s(x0) + s(x1) + s(x2) + s(x3), ~1), data = dat, family = gaulss ) link(mod, parameter = "scale") inv_link(mod, parameter = "scale") ## Works with `family` objects too link(shash(), parameter = "skewness")load_mgcv() link(gaussian()) link(nb()) inv_link(nb()) dat <- data_sim("eg1", seed = 4234) mod <- gam(list(y ~ s(x0) + s(x1) + s(x2) + s(x3), ~1), data = dat, family = gaulss ) link(mod, parameter = "scale") inv_link(mod, parameter = "scale") ## Works with `family` objects too link(shash(), parameter = "skewness")
Simple function that loads the mgcv package whilst suppressing the startup messages that it prints to the console.
load_mgcv()load_mgcv()
Returns a logical vectors invisibly, indicating whether the package was loaded or not.
Evaluate each fitting observation at draws from the coefficient posterior.
This leaves the scalar stats::logLik() method supplied by mgcv unchanged.
log_lik(model, ...) ## S3 method for class 'gam' log_lik( model, ..., n_draws = NULL, chains = NULL, diagnostics = FALSE, seed = NULL, method = c("gaussian", "mh", "user"), draws = NULL, unconditional = FALSE ) ## S3 method for class 'bam' log_lik( model, ..., n_draws = NULL, chains = NULL, diagnostics = FALSE, seed = NULL, method = c("gaussian", "mh", "user"), draws = NULL, unconditional = FALSE ) ## S3 method for class 'scam' log_lik(model, ..., unconditional = FALSE)log_lik(model, ...) ## S3 method for class 'gam' log_lik( model, ..., n_draws = NULL, chains = NULL, diagnostics = FALSE, seed = NULL, method = c("gaussian", "mh", "user"), draws = NULL, unconditional = FALSE ) ## S3 method for class 'bam' log_lik( model, ..., n_draws = NULL, chains = NULL, diagnostics = FALSE, seed = NULL, method = c("gaussian", "mh", "user"), draws = NULL, unconditional = FALSE ) ## S3 method for class 'scam' log_lik(model, ..., unconditional = FALSE)
model |
A fitted independent-response |
... |
Additional arguments to |
n_draws |
Positive integer; total coefficient draws across chains. Defaults to 4000 when generating draws. Supplied draws determine their own count; an explicit count must agree. |
chains |
positive integer or |
diagnostics |
logical; calculate coefficient R-hat, effective sample sizes, and Monte Carlo standard errors using the optional posterior package. |
seed |
Optional random seed. The caller's random-number state is retained. |
method |
One of |
draws |
A numeric matrix with one row per draw and one column per
coefficient, in fitted coefficient order. Used with |
unconditional |
Include the smoothing-parameter covariance correction
when available, using |
The result contains log densities or log probability masses, including their
normalising constants and fitting weights. Smoothing penalties and priors
are excluded. Likelihood weights need not have the same interpretation as
the weights used by posterior_samples() to generate responses.
Ordinary and extended response families, distributional GAMs, multinomial,
multivariate-normal and grouped families are supported. A multivariate-normal
observation contributes one joint log density; its precision coefficients
vary with each draw. Grouped observations use their fitted component family.
Custom families can supply the log_lik hook in family_diagnostics. Quasi,
censored and Cox families, residual-correlated BAMs and full mixed models
are not supported. Only retained fitting observations are evaluated.
Gaussian draws approximate the coefficient posterior. Parameters represented
by coefficients vary jointly, including distributional-model scale and shape
predictors. Other scale, shape and smoothing parameters remain at fitted
values. Even with unconditional = TRUE, those additional parameters are
not jointly sampled. Ordinary PSIS-LOO uses these draws without correcting
their Gaussian approximation. Pareto diagnostics assess reweighting, not the
accuracy of the Gaussian approximation. See loo.gam for optional loo methods.
Independent-response SCAM fits are supported using the coefficient
approximation selected by post_draws(). The prediction matrix multiplies
transformed coefficients. Smoothing parameters and response scale remain at
their fitted values; smoothing-parameter uncertainty is unavailable.
A numeric matrix with draws in rows and retained fitting observations
in columns. Attribute observation gives their original fitting-row indices
after any fitting subset; gratia describes the sampling assumptions.
The sampling attribute retains chain identities and requested coefficient
diagnostics; as_mcmc_draws() converts the likelihood matrix by chain.
Impossible observations may have log likelihood -Inf; invalid numerical
calculations produce an error. LOO and WAIC require finite log likelihoods.
posterior_samples(), family_diagnostics
load_mgcv() m <- gam(mpg ~ s(wt, k = 5), data = mtcars, method = "REML") ll <- log_lik(m, n_draws = 500, seed = 42) dim(ll) if (requireNamespace("loo", quietly = TRUE)) { loo::loo(ll, r_eff = 1) }load_mgcv() m <- gam(mpg ~ s(wt, k = 5), data = mtcars, method = "REML") ll <- log_lik(m, n_draws = 500, seed = 42) dim(ll) if (requireNamespace("loo", quietly = TRUE)) { loo::loo(ll, r_eff = 1) }
These methods evaluate the likelihood of each fitting observation at
posterior coefficient draws and return the usual objects from loo.
Neither method changes stats::logLik() for fitted GAMs.
loo.gam( x, ..., n_draws = NULL, seed = NULL, sampling_args = list(), r_eff = NULL, chain_id = NULL, save_psis = FALSE, cores = 1 ) loo.bam( x, ..., n_draws = NULL, seed = NULL, sampling_args = list(), r_eff = NULL, chain_id = NULL, save_psis = FALSE, cores = 1 ) waic.gam(x, ..., n_draws = NULL, seed = NULL, sampling_args = list()) waic.bam(x, ..., n_draws = NULL, seed = NULL, sampling_args = list()) loo.scam(x, ...) waic.scam(x, ...)loo.gam( x, ..., n_draws = NULL, seed = NULL, sampling_args = list(), r_eff = NULL, chain_id = NULL, save_psis = FALSE, cores = 1 ) loo.bam( x, ..., n_draws = NULL, seed = NULL, sampling_args = list(), r_eff = NULL, chain_id = NULL, save_psis = FALSE, cores = 1 ) waic.gam(x, ..., n_draws = NULL, seed = NULL, sampling_args = list()) waic.bam(x, ..., n_draws = NULL, seed = NULL, sampling_args = list()) loo.scam(x, ...) waic.scam(x, ...)
x |
a GAM or BAM fitted by mgcv, or an independent-response SCAM fitted by scam. |
... |
additional arguments passed to |
n_draws |
total posterior coefficient draws across all chains. Defaults to 4000 when generating draws; supplied draws determine their own count. |
seed |
random seed for posterior sampling. |
sampling_args |
named list of arguments passed to the coefficient
sampler, including |
r_eff |
optional relative effective sample sizes, either one value or
one per observation. Independent Gaussian draws use |
chain_id |
integer chain identifier for each coefficient draw, in draw order. Identifiers must be consecutive starting at one, and chains must contain equal numbers of draws. A supplied mapping must agree with the coefficient draws' stored mapping. Stored iterations determine temporal order for relative efficiency without reordering response or likelihood rows. |
save_psis |
retain the PSIS object in the returned LOO result. |
cores |
number of cores used by loo. |
The Gaussian posterior approximation and fitted values of additional family
parameters are described in log_lik(). PSIS diagnostics assess the
importance weights; they do not measure the accuracy of that approximation.
With random-effect smooths, leaving out individual observations predicts
further observations in the fitted groups, rather than new groups.
Likelihoods are evaluated one observation at a time using the function interface in loo. Saving PSIS weights still requires storage proportional to the number of observations times the number of draws.
A native loo or waic object, with attributes gratia describing
posterior sampling assumptions and observation identifying fitting rows.
if (requireNamespace("loo", quietly = TRUE)) { load_mgcv() m <- gam(mpg ~ s(wt, k = 5), data = mtcars, method = "REML") loo::loo(m, n_draws = 500, seed = 42) }if (requireNamespace("loo", quietly = TRUE)) { load_mgcv() m <- gam(mpg ~ s(wt, k = 5), data = mtcars, method = "REML") loo::loo(m, n_draws = 500, seed = 42) }
lp_matrix() is a wrapper to predict(..., type = "lpmatrix") for returning
the linear predictor matrix for the model training data (when data = NULL),
or user-specified data values supplied via data.
## S3 method for class 'gamm4' lp_matrix(model, ...) lp_matrix(model, ...) ## S3 method for class 'gam' lp_matrix(model, data = NULL, ...) ## S3 method for class 'scam' lp_matrix(model, data = NULL, ...) ## S3 method for class 'scam' model.matrix(object, ...)## S3 method for class 'gamm4' lp_matrix(model, ...) lp_matrix(model, ...) ## S3 method for class 'gam' lp_matrix(model, data = NULL, ...) ## S3 method for class 'scam' lp_matrix(model, data = NULL, ...) ## S3 method for class 'scam' model.matrix(object, ...)
model |
a fitted model |
... |
arguments passed to other methods and |
data |
a data frame of values at which to return the linear prediction matrix. |
object |
a fitted SCAM model, for the |
The linear prediction matrix is a matrix that maps values
of parameters to values on the linear
predictor of the model , where contains
known additive contributions such as formula offsets and prescribed smooth
boundary values. These contributions are not coefficient columns of
. Native prediction may attach them as model.offset
(formula offsets, by linear predictor) or offset (fixed smooth
contributions, by smooth) attributes. Matrix multiplication alone does not
add these attributes. is the model matrix where spline
covariates have been replaced by the values of the basis functions evaluated
at the respective covariates. Parametric covariates are also included.
The linear prediction matrix is returned as a matrix. The object
returned is of class "lp_matrix", which inherits from classes "matrix"
and "array". The special class allows the printing of the matrix to be
controlled, which we do by printing the matrix as a tibble.
load_mgcv() df <- data_sim("eg1", seed = 1) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df) # linear prediction matrix for observed data xp <- lp_matrix(m) ## IGNORE_RDIFF_BEGIN xp ## IGNORE_RDIFF_END # the object `xp` *is* a matrix class(xp) # but we print like a tibble to avoid spamming the R console # linear predictor matrix for new data set ds <- data_slice(m, x2 = evenly(x2)) xp <- lp_matrix(m, data = ds) ## IGNORE_RDIFF_BEGIN xp ## IGNORE_RDIFF_ENDload_mgcv() df <- data_sim("eg1", seed = 1) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df) # linear prediction matrix for observed data xp <- lp_matrix(m) ## IGNORE_RDIFF_BEGIN xp ## IGNORE_RDIFF_END # the object `xp` *is* a matrix class(xp) # but we print like a tibble to avoid spamming the R console # linear predictor matrix for new data set ds <- data_slice(m, x2 = evenly(x2)) xp <- lp_matrix(m, data = ds) ## IGNORE_RDIFF_BEGIN xp ## IGNORE_RDIFF_END
Posterior samples using Metropolis Hastings
## S3 method for class 'gamm4' mh_draws(model, ...) mh_draws(model, ...) ## S3 method for class 'gam' mh_draws( model, ..., n_draws = NULL, chains = NULL, n_cores = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), block_size = 10000L, dense_limit = 5e+06, index = NULL, seed = NULL ) ## S3 method for class 'scam' mh_draws(model, ...)## S3 method for class 'gamm4' mh_draws(model, ...) mh_draws(model, ...) ## S3 method for class 'gam' mh_draws( model, ..., n_draws = NULL, chains = NULL, n_cores = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), block_size = 10000L, dense_limit = 5e+06, index = NULL, seed = NULL ) ## S3 method for class 'scam' mh_draws(model, ...)
model |
a fitted model from |
... |
arguments passed to methods. |
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
chains |
positive integer or |
n_cores |
positive integer; maximum concurrent MH chains using mirai,
capped at |
burnin |
numeric; the length of any initial burn in period to discard.
See |
thin |
positive integer; retain every |
t_df |
numeric; degrees of freedom for static multivariate t proposal.
See |
rw_scale |
numeric; factor by which to scale posterior covariance
matrix when generating random walk proposals. See |
diagnostics |
logical; calculate coefficient R-hat, effective sample sizes, and Monte Carlo standard errors using the optional posterior package. |
mh_backend |
character; |
block_size |
positive integer; maximum observation rows per block in the gratia MH evaluator. Large designs are evaluated without storing a full matrix. |
dense_limit |
numeric; maximum number of design-matrix elements to cache for the gratia MH backend. Use zero to force blockwise evaluation. |
index |
numeric; vector of indices of coefficients to use. Can be used
to subset the mean vector and covariance matrix extracted from |
seed |
numeric or |
Sampling controls must be named. Removed arguments produce migration errors;
see vignette("sampling-migration"). Explicit controls that the selected
method cannot use are rejected.
For SCAM models, Gaussian draws approximate the distribution of the unrestricted
fitting coefficients using Vp (or Ve with frequentist = TRUE), then apply
scam's fitted exponential or notExp transformation. This is an approximation
in fitting coordinates, rather than an exact constrained posterior. Supplied
draws must already use the transformed coordinates in coef(model) order.
Numerically singular covariance matrices are sampled by eigen decomposition;
negative eigenvalues within 100 * .Machine$double.eps * ncol(V) times the
largest absolute eigenvalue are treated as zero. Larger negatives are errors.
For weakly identified exponential coefficients, a very large fitting-coordinate
variance can yield non-finite transformed draws. Sampling then reports an
error because this Gaussian approximation cannot provide usable draws; supply
finite transformed draws from a suitable alternative sampler.
For multiple chains, n_draws is the total retained count and must be divisible
by chains. Coefficient matrices carry a chain mapping; use
as_mcmc_draws() before ordinary matrix operations remove that mapping.
Higher-level sampling tables include .chain and .iteration for multiple
chains, with .draw unique across chains. Default single-chain table columns
are unchanged. Use sampling_diagnostics() to extract coefficient diagnostics
before response simulation adds further noise.
The gratia MH backend supports Gaussian identity, Poisson log, binomial
logit, Gamma log, and negative binomial log fits. It evaluates the fitted
bases at original covariates, including for discrete bam fits. GAMM components, AR1 dependence,
paraPen, H, and fits made from pre-fit G objects are unsupported.
The family MH backend calls the fitted family's dev.resids() and linkinv()
functions, or ll() for families with multiple linear predictors. This
retains response encodings and attributes such as censoring indicators and
the mappings between coefficients and predictors. It supports compatible
standard, extended, and general mgcv families, including multinomial, Gaussian
location-scale, and grouped families. Quasi families, Cox proportional hazards
models, GAMM components, AR1 dependence, paraPen, H, and pre-fit G objects
are unsupported. The fitted coefficient covariance must be nonsingular.
It always caches the full design matrix; block_size and dense_limit apply
only to the gratia backend and are rejected for the family backend.
The new MH backends reject bam fits with nonzero prescribed smooth
contributions: mgcv fitting and prediction can use different offsets for
those fits. Supplied coefficient draws can still be evaluated with the
native prediction conventions.
All MH backends sample the conditional coefficient posterior with fitted
smoothing, dispersion, and additional family parameters fixed. Parameters
represented in the fitted coefficient vector are sampled, including scale
or covariance coefficients in general families. unconditional applies
to Gaussian draws only.
GAM-class fits with linear inequality constraints, including
mgcv::scasm() fits, store these as Ain %*% coefficients >= bin.
Gaussian sampling uses the fitted covariance matrix without enforcing
these inequalities and issues a warning. Sampled smooths can therefore
violate the fitted shape constraints. Pointwise intervals computed from
the same Gaussian covariance approximation also need not preserve those
shapes. All MH backends are unavailable for these fits because
the samplers do not enforce their inequalities.
If mgcv::scasm() was fitted with bs > 0, its bs component stores
coefficient draws from the native constrained bootstrap in columns. These
can be supplied explicitly as draws = t(model$bs) with method = "user".
The result then describes bootstrap variation, rather than Gaussian
posterior sampling. Gratia does not automatically select these draws.
The caller is responsible for the interpretation and constraint
feasibility of user-supplied draws.
Concurvity of an estimated GAM
model_concurvity(model, ...) ## S3 method for class 'gam' model_concurvity( model, terms = everything(), type = c("all", "estimate", "observed", "worst"), pairwise = FALSE, ... ) concrvity( model, terms = everything(), type = c("all", "estimate", "observed", "worst"), pairwise = FALSE, ... ) ## S3 method for class 'gamm4' model_concurvity(model, ...) ## S3 method for class 'scam' model_concurvity(model, ...)model_concurvity(model, ...) ## S3 method for class 'gam' model_concurvity( model, terms = everything(), type = c("all", "estimate", "observed", "worst"), pairwise = FALSE, ... ) concrvity( model, terms = everything(), type = c("all", "estimate", "observed", "worst"), pairwise = FALSE, ... ) ## S3 method for class 'gamm4' model_concurvity(model, ...) ## S3 method for class 'scam' model_concurvity(model, ...)
model |
a fitted GAM. Currently only objects of class |
... |
arguments passed to other methods. |
terms |
currently ignored |
type |
character; |
pairwise |
logical; extract pairwise concurvity of model terms? |
## simulate data with concurvity... library("tibble") load_mgcv() set.seed(8) n <- 200 df <- tibble( t = sort(runif(n)), x = gw_f2(t) + rnorm(n) * 3, y = sin(4 * pi * t) + exp(x / 20) + rnorm(n) * 0.3 ) ## fit model m <- gam(y ~ s(t, k = 15) + s(x, k = 15), data = df, method = "REML") ## overall concurvity o_conc <- concrvity(m) draw(o_conc) ## pairwise concurvity p_conc <- concrvity(m, pairwise = TRUE) draw(p_conc)## simulate data with concurvity... library("tibble") load_mgcv() set.seed(8) n <- 200 df <- tibble( t = sort(runif(n)), x = gw_f2(t) + rnorm(n) * 3, y = sin(4 * pi * t) + exp(x / 20) + rnorm(n) * 0.3 ) ## fit model m <- gam(y ~ s(t, k = 15) + s(x, k = 15), data = df, method = "REML") ## overall concurvity o_conc <- concrvity(m) draw(o_conc) ## pairwise concurvity p_conc <- concrvity(m, pairwise = TRUE) draw(p_conc)
Extracts the model constant term(s),
the model intercept, from a fitted model object. Predictors without an
intercept return zero.
## S3 method for class 'gamm4' model_constant(model, ...) model_constant(model, ...) ## S3 method for class 'gam' model_constant(model, lp = NULL, ...) ## S3 method for class 'gamlss' model_constant(model, ...) ## S3 method for class 'glm' model_constant(model, ...) ## S3 method for class 'scam' model_constant(model, lp = NULL, ...)## S3 method for class 'gamm4' model_constant(model, ...) model_constant(model, ...) ## S3 method for class 'gam' model_constant(model, lp = NULL, ...) ## S3 method for class 'gamlss' model_constant(model, ...) ## S3 method for class 'glm' model_constant(model, ...) ## S3 method for class 'scam' model_constant(model, lp = NULL, ...)
model |
a fitted model for which a |
... |
arguments passed to other methods. |
lp |
numeric; which linear predictors to extract constant terms for. |
load_mgcv() # simulate a small example df <- data_sim("eg1", seed = 42) # fit the GAM m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # extract the estimate of the constant term model_constant(m) # same as coef(m)[1L] coef(m)[1L]load_mgcv() # simulate a small example df <- data_sim("eg1", seed = 42) # fit the GAM m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # extract the estimate of the constant term model_constant(m) # same as coef(m)[1L] coef(m)[1L]
Returns the names of any terms in a model, without needing to call
summary(). The list of model terms is especially useful when predicting
from a mgcv::gam() model using the exclude or terms argument of
mgcv::predict.gam() or mgcv::predict.bam().
model_terms(object, ...) ## S3 method for class 'gam' model_terms(object, ...) ## S3 method for class 'gamm' model_terms(object, ...) ## S3 method for class 'gamm4' model_terms(object, ...) ## S3 method for class 'lm' model_terms(object, ...) ## S3 method for class 'scam' model_terms(object, ...)model_terms(object, ...) ## S3 method for class 'gam' model_terms(object, ...) ## S3 method for class 'gamm' model_terms(object, ...) ## S3 method for class 'gamm4' model_terms(object, ...) ## S3 method for class 'lm' model_terms(object, ...) ## S3 method for class 'scam' model_terms(object, ...)
object |
a fitted model. |
... |
arguments to be passed to other methods; not currently used. |
From the point of view of gratia, models contain two types of term:
parametric terms, and
smooth terms.
If we consider the formula y ~ fac + s(x2, by = fac) + s(x0), for a factor
fac with three levels, there are seven terms in the model:
the model constant term, with name "(Intercept)",
the parametric factor term, with names
fac2,
fac3,
the univariate smooth of x0, named "s(x0)", and
the three factor-by smooths with names
"s(x2):fac1",
"s(x2):fac2", and
"s(x2):fac3".'
model_terms() will return a vector of those names.
A character vector of model terms.
load_mgcv() # simulate data df <- data_sim("eg4", n = 400, dist = "normal", scale = 2, seed = 1) # fit model m <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = df, method = "REML") # return the names of terms in this model model_terms(m)load_mgcv() # simulate data df <- data_sim("eg4", n = 400, dist = "normal", scale = 2, seed = 1) # fit model m <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = df, method = "REML") # return the names of terms in this model model_terms(m)
List the variables involved in a model fitted with a formula
model_vars(model, ...) ## S3 method for class 'gam' model_vars(model, ...) ## Default S3 method: model_vars(model, ...) ## S3 method for class 'bam' model_vars(model, ...) ## S3 method for class 'gamm' model_vars(model, ...) ## S3 method for class 'gamm4' model_vars(model, ...) ## S3 method for class 'scam' model_vars(model, ...)model_vars(model, ...) ## S3 method for class 'gam' model_vars(model, ...) ## Default S3 method: model_vars(model, ...) ## S3 method for class 'bam' model_vars(model, ...) ## S3 method for class 'gamm' model_vars(model, ...) ## S3 method for class 'gamm4' model_vars(model, ...) ## S3 method for class 'scam' model_vars(model, ...)
model |
a fitted model object with a |
... |
Arguments passed to other methods. Currently ignored. |
load_mgcv() # simulate some Gaussian data df <- data_sim("eg1", n = 50, seed = 2) # fit a GAM with 1 smooth and 1 linear term m1 <- gam(y ~ s(x2, k = 7) + x1, data = df, method = "REML") model_vars(m1) # fit a lm with two linear terms m2 <- lm(y ~ x2 + x1, data = df) model_vars(m2)load_mgcv() # simulate some Gaussian data df <- data_sim("eg1", n = 50, seed = 2) # fit a GAM with 1 smooth and 1 linear term m1 <- gam(y ~ s(x2, k = 7) + x1, data = df, method = "REML") model_vars(m1) # fit a lm with two linear terms m2 <- lm(y ~ x2 + x1, data = df) model_vars(m2)
Extracts the number of linear predictors
from the fitted model.
## S3 method for class 'gamm4' n_eta(model, ...) ## S3 method for class 'scam' n_eta(model, ...) n_eta(model, ...) ## S3 method for class 'gam' n_eta(model, ...)## S3 method for class 'gamm4' n_eta(model, ...) ## S3 method for class 'scam' n_eta(model, ...) n_eta(model, ...) ## S3 method for class 'gam' n_eta(model, ...)
model |
a fitted model. Currently, only models inheriting from class
|
... |
arguments passed to methods. |
An integer vector of length 1 containing the number of linear predictors in the model.
How many smooths in a fitted model
## S3 method for class 'gamm4' n_smooths(object) ## S3 method for class 'gjrm' n_smooths(object) ## S3 method for class 'glmmTMB' n_smooths(object) n_smooths(object) ## Default S3 method: n_smooths(object) ## S3 method for class 'gam' n_smooths(object) ## S3 method for class 'gamm' n_smooths(object) ## S3 method for class 'bam' n_smooths(object)## S3 method for class 'gamm4' n_smooths(object) ## S3 method for class 'gjrm' n_smooths(object) ## S3 method for class 'glmmTMB' n_smooths(object) n_smooths(object) ## Default S3 method: n_smooths(object) ## S3 method for class 'gam' n_smooths(object) ## S3 method for class 'gamm' n_smooths(object) ## S3 method for class 'bam' n_smooths(object)
object |
a fitted GAM or related model. Typically the result of a call
to |
For glmmTMB models, n_smooths() counts smooth terms across the
conditional, zero-inflation and dispersion predictors. Each fitted smooth
is counted once; native random effects are excluded. Models without smooths
return integer zero.
Negative binomial parameter theta
nb_theta(model) ## S3 method for class 'gam' nb_theta(model) ## S3 method for class 'gamm4' nb_theta(model)nb_theta(model) ## S3 method for class 'gam' nb_theta(model) ## S3 method for class 'gamm4' nb_theta(model)
model |
a fitted model. |
A numeric vector of length 1 containing the estimated value of theta.
nb_theta(gam): Method for class "gam"
load_mgcv() df <- data_sim("eg1", n = 500, dist = "poisson", scale = 0.1, seed = 6) m <- gam(y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, bs = "cr") + s(x3, bs = "cr"), family = nb, data = df, method = "REML") ## IGNORE_RDIFF_BEGIN nb_theta(m) ## IGNORE_RDIFF_ENDload_mgcv() df <- data_sim("eg1", n = 500, dist = "poisson", scale = 0.1, seed = 6) m <- gam(y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, bs = "cr") + s(x3, bs = "cr"), family = nb, data = df, method = "REML") ## IGNORE_RDIFF_BEGIN nb_theta(m) ## IGNORE_RDIFF_END
Extract the null deviance of a fitted model
null_deviance(model, ...) ## Default S3 method: null_deviance(model, ...)null_deviance(model, ...) ## Default S3 method: null_deviance(model, ...)
model |
a fitted model |
... |
arguments passed to other methods |
Plot of fitted against observed response values
observed_fitted_plot( model, ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, point_col = "grey20", point_alpha = 1, by_family = NULL, conditioning = NULL, ... )observed_fitted_plot( model, ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, point_col = "grey20", point_alpha = 1, by_family = NULL, conditioning = NULL, ... )
model |
a fitted model supported by diagnostic_support. |
ylab |
character or expression; the label for the y axis. If not supplied, a suitable label will be generated. |
xlab |
character or expression; the label for the x axis. If not supplied, a suitable label will be generated. |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
point_col |
Deprecated; use |
point_alpha |
Deprecated; use |
by_family |
logical or |
conditioning |
character or |
... |
optional arguments passed to model preparation, such as the
sdmTMB |
Provides an overview of a model and the terms in that model
## S3 method for class 'gamm4' overview(model, ...) overview(model, ...) ## S3 method for class 'gam' overview( model, parametric = TRUE, random_effects = TRUE, dispersion = NULL, frequentist = FALSE, accuracy = 0.001, digits = 3, stars = FALSE, ... ) ## S3 method for class 'scam' overview(model, ...)## S3 method for class 'gamm4' overview(model, ...) overview(model, ...) ## S3 method for class 'gam' overview( model, parametric = TRUE, random_effects = TRUE, dispersion = NULL, frequentist = FALSE, accuracy = 0.001, digits = 3, stars = FALSE, ... ) ## S3 method for class 'scam' overview(model, ...)
model |
a fitted model object to overview. |
... |
arguments passed to other methods. |
parametric |
logical; include the model parametric terms in the overview? |
random_effects |
tests of fully penalized smooth terms (those with a
zero-dimensional null space, e.g. random effects) are computationally
expensive and for large data sets producing these p values can take a
very long time. If |
dispersion |
numeric; a known value for the dispersion parameter. The
default |
frequentist |
logical; by default the Bayesian estimated covariance
matrix of the parameter estimates is used to calculate p values for
parametric terms. If |
accuracy |
numeric; accuracy with which to report p values, with p
values below this value displayed as |
digits |
numeric; the number of significant digits to be used. |
stars |
logical; should significance stars be added to the output? |
load_mgcv() df <- data_sim(n = 400, seed = 2) m <- gam(y ~ x3 + s(x0) + s(x1, bs = "bs") + s(x2, bs = "ts"), data = df, method = "REML" ) overview(m)load_mgcv() df <- data_sim(n = 400, seed = 2) m <- gam(y ~ x3 + s(x0) + s(x1, bs = "bs") + s(x2, bs = "ts"), data = df, method = "REML" ) overview(m)
Estimated values for parametric model terms
## S3 method for class 'gamm4' parametric_effects(object, ...) parametric_effects(object, ...) ## S3 method for class 'gam' parametric_effects( object, terms = NULL, data = NULL, unconditional = FALSE, unnest = TRUE, ci_level = 0.95, envir = NULL, transform = lifecycle::deprecated(), n = 100, n_2d = 50, n_3d = 16, n_4d = 4, dist = 0.1, overall_uncertainty = TRUE, back_transform = FALSE, ... ) ## S3 method for class 'scam' parametric_effects(object, ..., unconditional = FALSE)## S3 method for class 'gamm4' parametric_effects(object, ...) parametric_effects(object, ...) ## S3 method for class 'gam' parametric_effects( object, terms = NULL, data = NULL, unconditional = FALSE, unnest = TRUE, ci_level = 0.95, envir = NULL, transform = lifecycle::deprecated(), n = 100, n_2d = 50, n_3d = 16, n_4d = 4, dist = 0.1, overall_uncertainty = TRUE, back_transform = FALSE, ... ) ## S3 method for class 'scam' parametric_effects(object, ..., unconditional = FALSE)
object |
a fitted model object. |
... |
arguments passed to other methods. |
terms |
character; which model parametric terms should be drawn? The
Default of |
data |
an optional data frame containing raw model covariates at which to evaluate parametric effects. By default, stored raw columns are used; missing raw inputs are recovered from the fitting data when possible. |
unconditional |
logical; should confidence intervals include the
uncertainty due to smoothness selection? If |
unnest |
logical; unnest the parametric effect objects? |
ci_level |
numeric; the coverage required for the confidence interval. Currently ignored. |
envir |
an optional environment for local functions and constants, and for recovering fitting data when required raw columns are not stored in the model. Defaults to the model's evaluation environment. |
transform |
|
n, n_2d, n_3d, n_4d
|
Grid resolutions for multivariate parametric terms.
Curves use |
dist |
Non-negative distance for masking surface plots far from observed
covariates, as in |
overall_uncertainty |
logical; include uncertainty in the intercept of
the term's linear predictor, including its covariance with the term?
Defaults to |
back_transform |
logical; plot covariates on their original scale?
Defaults to |
Each estimate is the contribution of one formula term to its linear predictor. Intercepts, main effects and other terms are not added to an interaction. Components follow the model's contrast coding: with treatment contrasts, a numeric-by-factor interaction represents a departure from the reference-level slope, rather than a complete slope for each level.
For sdmTMB time-varying coefficients, .type = "time_varying" identifies
coefficient trajectories. In these rows, .value contains time, .partial
contains the full coefficient, and .se includes the joint uncertainty of
its ordinary coefficient and temporal deviation. Default selection omits
ordinary terms already included in these trajectories; their usual selectors
remain available for explicit requests. See sdmTMB-methods for details.
A multi-column term such as poly(x, 3) is one component, whereas x and
I(x^2) remain separate components. Scalar numeric transformations use model
coordinates by default, including each axis of an interaction. Basis
expansions such as poly(x, 3), terms combining several inputs in one
expression, and interactions containing several transformations of the same
input retain raw axes because they have no single model coordinate per input.
Other covariates in generated prediction data are held at typical values
solely to evaluate the model matrix; their contributions are not included.
Rugs show fitting observations, including when prediction data are
supplied. If fitting observations cannot be recovered, these rugs are omitted.
The drawing method uses the first two numeric covariates for surface axes, grouping curves by the first factor when there is only one numeric covariate. Factor-only terms use grouped points and intervals. Remaining covariates define facets: one wraps, two or more use the first as rows and the rest as columns. Formula order is retained within numeric and discrete covariates. Logical covariates are discrete. Surface plots show estimates; uncertainty is retained in the returned data rather than drawn as additional surfaces.
For models with multiple linear predictors, plot subtitles identify each
term's distributional parameter or model component, as for smooth plots.
Shared terms name every predictor to which they contribute. The optional
.model column retains these labels, including with unnest = FALSE.
Single-predictor models omit automatic subtitles. Older saved estimates
remain drawable when predictor labels are absent.
A tibble of class parametric_effects, with .term, .type,
.partial and .se. Single-variable terms retain .value or .level;
multivariate terms use columns named for their raw covariates, containing
coordinates on the selected scale. Names conflicting
with reserved columns are repaired with numeric suffixes. The term_info
attribute records multivariate column mappings, plotting order, factor
levels and observation data. With unnest = FALSE, estimates and
covariates are nested in a data list column. The axis_info attribute
identifies retained raw and model coordinate columns and their labels
so the drawing method
can select either scale. The back_transform attribute records the scale
of the returned coordinate columns. Auxiliary .gratia_raw_* and
.gratia_model_* columns retain both scales for transformed axes.
load_mgcv() # Simulate numeric and factor effects set.seed(42) d <- data.frame( x = runif(100), group = factor(rep(c("A", "B"), each = 50)) ) d$y <- with(d, 2 * x + (group == "B") + rnorm(100, sd = 0.25)) m <- gam(y ~ x + group, data = d, method = "REML") # Estimate and draw the contribution of each parametric term pe <- parametric_effects(m) pe draw(pe)load_mgcv() # Simulate numeric and factor effects set.seed(42) d <- data.frame( x = runif(100), group = factor(rep(c("A", "B"), each = 50)) ) d$y <- with(d, 2 * x + (group == "B") + rnorm(100, sd = 0.25)) m <- gam(y ~ x + group, data = d, method = "REML") # Estimate and draw the contribution of each parametric term pe <- parametric_effects(m) pe draw(pe)
Names of any parametric terms in a GAM
## S3 method for class 'gamm4' parametric_terms(model, ...) ## S3 method for class 'scam' parametric_terms(model, ...) parametric_terms(model, ...) ## Default S3 method: parametric_terms(model, ...) ## S3 method for class 'gam' parametric_terms(model, ...)## S3 method for class 'gamm4' parametric_terms(model, ...) ## S3 method for class 'scam' parametric_terms(model, ...) parametric_terms(model, ...) ## Default S3 method: parametric_terms(model, ...) ## S3 method for class 'gam' parametric_terms(model, ...)
model |
a fitted model. |
... |
arguments passed to other methods. |
Partial derivatives of estimated multivariate smooths via finite differences
partial_derivatives(object, ...) ## Default S3 method: partial_derivatives(object, ...) ## S3 method for class 'gamm' partial_derivatives(object, ...) ## S3 method for class 'gam' partial_derivatives( object, select = NULL, term = deprecated(), focal = NULL, data = newdata, order = 1L, type = c("forward", "backward", "central"), n = 100, eps = NULL, interval = c("confidence", "simultaneous"), n_sim = 10000, level = 0.95, unconditional = FALSE, frequentist = FALSE, offset = NULL, ncores = 1, partial_match = FALSE, seed = NULL, ..., newdata = NULL, envir = NULL, wrt = c("smooth", "covariate"), interval_method = c("auto", "gaussian", "bootstrap"), simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list() ) ## S3 method for class 'gamm4' partial_derivatives(object, ...) ## S3 method for class 'scam' partial_derivatives(object, ..., unconditional = FALSE)partial_derivatives(object, ...) ## Default S3 method: partial_derivatives(object, ...) ## S3 method for class 'gamm' partial_derivatives(object, ...) ## S3 method for class 'gam' partial_derivatives( object, select = NULL, term = deprecated(), focal = NULL, data = newdata, order = 1L, type = c("forward", "backward", "central"), n = 100, eps = NULL, interval = c("confidence", "simultaneous"), n_sim = 10000, level = 0.95, unconditional = FALSE, frequentist = FALSE, offset = NULL, ncores = 1, partial_match = FALSE, seed = NULL, ..., newdata = NULL, envir = NULL, wrt = c("smooth", "covariate"), interval_method = c("auto", "gaussian", "bootstrap"), simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list() ) ## S3 method for class 'gamm4' partial_derivatives(object, ...) ## S3 method for class 'scam' partial_derivatives(object, ..., unconditional = FALSE)
object |
an R object to compute derivatives for. |
... |
arguments passed to other methods. |
select |
character; vector of one or more smooth terms for which
derivatives are required. If missing, derivatives for all smooth terms
will be returned. Can be a partial match to a smooth term; see argument
|
term |
|
focal |
character; name of the focal variable. The partial derivative
of the estimated smooth with respect to this variable will be returned.
All other variables involved in the smooth will be held at constant. This
can be missing if supplying |
data |
a data frame containing the values of the model covariates at which to evaluate the first derivatives of the smooths. If supplied, all but one variable must be held at a constant value. |
order |
numeric; the order of derivative. |
type |
character; the type of finite difference used. One of
|
n |
numeric; the number of points to evaluate the derivative at. |
eps |
a positive finite number giving the absolute finite-difference
step, or |
interval |
character; the type of interval to compute. One of
|
n_sim |
integer; the number of simulations used in computing the simultaneous intervals. |
level |
numeric; |
unconditional |
logical; use smoothness selection-corrected Bayesian covariance matrix? |
frequentist |
logical; use the frequentist covariance matrix? |
offset |
numeric; a value to use for any offset term |
ncores |
number of cores for generating random variables from a
multivariate normal distribution. Passed to |
partial_match |
logical; should smooths be selected by partial matches
with |
seed |
numeric; RNG seed to use. |
newdata |
Deprecated: use |
envir |
optional environment for functions and constants in model
expressions; see |
wrt |
differentiation coordinate: |
interval_method |
character; use stored scasm bootstrap draws for
pointwise intervals with |
simultaneous_method |
character; calibration for simultaneous bands.
The default, |
simultaneous_domain |
numeric pair of increasing finite endpoints, or
a named list of such pairs keyed by spline coordinate. For tube bands,
|
tube_control |
named list controlling numerical tube calibration:
|
A tibble, currently with the following variables:
.smooth: the smooth each row refers to,
.partial_deriv: the estimated partial derivative,
.se: the standard error of the estimated partial derivative,
.crit: the critical value such that derivative ± (crit * se) gives
the upper and lower bounds of the requested confidence or simultaneous
interval (given level); NA for bootstrap limits,
.lower_ci: the lower bound of the confidence or simultaneous interval,
.upper_ci: the upper bound of the confidence or simultaneous interval.
With mirai and carrier installed, configure workers with
mirai::daemons() to distribute calculations across selected smooths.
difference_smooths() distributes factor-level comparisons instead.
Without configured workers, or with only one calculation, evaluation is
serial. These functions leave the caller's worker pool running.
Model selection, evaluation of model expressions and random draws are
prepared in the caller. Workers receive the coordinates and coefficient
columns needed for their calculation. Custom prediction methods are evaluated
in the caller, including custom tensor margins and factor-smooth bases;
workers receive their prediction matrices. Simultaneous intervals use successive
draws in selection order, so set.seed() gives the same results with or
without workers, independently of their number or completion order.
derivatives() uses set.seed(); the other functions also accept seed,
which restores the caller's random number state on exit.
smooth_samples() draws coefficients jointly once, then reuses those draws
for every smooth, preserving dependence and chain identities. Sampling
finishes before smooth calculations start, so MH chains and smooth workers
are not nested. Sampling thread controls keep their existing meanings.
Workers use their configured BLAS thread settings; when using a threaded
BLAS, limit its threads before starting daemons to avoid competing threads.
Parallel work is most useful for expensive bases or interval calculations. Small grids can be slower because of transfer and scheduling costs. Large grids and many draws also require memory for worker inputs and returned results, in addition to the final output.
partial_derivatives() will ignore any random effect smooths it
encounters in object.
For soap-film smooths with known boundary values, derivatives include the
fixed boundary contribution. This shifts the estimates and interval limits
without adding uncertainty from fitted coefficients.
Gavin L. Simpson
difference_smooths() with order > 0 and focal to compute
partial derivatives of differences across full smooth surfaces.
load_mgcv() # Simulate a smooth surface with Gaussian noise and fit a tensor-product smooth df <- data_sim("eg2", n = 400, scale = 0.1, seed = 42) m <- gam(y ~ te(x, z, k = c(7, 7)), data = df, method = "REML") # Estimate change along x while holding z at 0.4 ds <- data_slice(m, x = evenly(x, n = 100), z = 0.4) pd_x <- partial_derivatives(m, data = ds, type = "central", focal = "x") pd_x draw(pd_x)load_mgcv() # Simulate a smooth surface with Gaussian noise and fit a tensor-product smooth df <- data_sim("eg2", n = 400, scale = 0.1, seed = 42) m <- gam(y ~ te(x, z, k = c(7, 7)), data = df, method = "REML") # Estimate change along x while holding z at 0.4 ds <- data_slice(m, x = evenly(x, n = 100), z = 0.4) pd_x <- partial_derivatives(m, data = ds, type = "central", focal = "x") pd_x draw(pd_x)
Partial residuals
partial_residuals(object, ...) ## S3 method for class 'gam' partial_residuals(object, select = NULL, partial_match = FALSE, ...) ## S3 method for class 'scam' partial_residuals(object, ...)partial_residuals(object, ...) ## S3 method for class 'gam' partial_residuals(object, select = NULL, partial_match = FALSE, ...) ## S3 method for class 'scam' partial_residuals(object, ...)
object |
an R object, typically a model. Currently only objects of
class |
... |
arguments passed to other methods. |
select |
character, logical, or numeric; which smooths to plot. If
|
partial_match |
logical; should smooths be selected by partial matches
with |
With na.exclude, excluded observations are restored as NA partial
residuals, in fitting order after any subset. With na.omit, only retained
observations are returned. Computation uses aligned working residuals,
working weights and term predictions before restoring excluded positions.
Partial residuals require working residuals and working weights from the
fitted model. Families that do not provide these, including the location-scale
families in mgcv, are not supported, even for terms in the location predictor.
## load mgcv load_mgcv() ## example data - Gu & Wahba four term model df <- data_sim("eg1", n = 400, seed = 42) ## fit the model m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## extract partial residuals partial_residuals(m) ## and for a select term partial_residuals(m, select = "s(x2)") ## or with partial matching partial_residuals(m, select = "x", partial_match = TRUE) # returns all## load mgcv load_mgcv() ## example data - Gu & Wahba four term model df <- data_sim("eg1", n = 400, seed = 42) ## fit the model m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## extract partial residuals partial_residuals(m) ## and for a select term partial_residuals(m, select = "s(x2)") ## or with partial matching partial_residuals(m, select = "x", partial_match = TRUE) # returns all
Extract and tidy penalty matrices
## S3 method for class 'gamm4' penalty(object, ...) penalty(object, ...) ## Default S3 method: penalty( object, rescale = FALSE, data, knots = NULL, constraints = FALSE, diagonalize = FALSE, margins = FALSE, ... ) ## S3 method for class 'gam' penalty( object, select = NULL, smooth = deprecated(), rescale = FALSE, partial_match = FALSE, margins = FALSE, ... ) ## S3 method for class 'mgcv.smooth' penalty(object, rescale = FALSE, ...) ## S3 method for class 'tensor.smooth' penalty(object, margins = FALSE, rescale = FALSE, ...) ## S3 method for class 't2.smooth' penalty(object, margins = FALSE, rescale = FALSE, ...) ## S3 method for class 're.smooth.spec' penalty(object, data, rescale = FALSE, margins = FALSE, ...) ## S3 method for class 'scam' penalty(object, ...)## S3 method for class 'gamm4' penalty(object, ...) penalty(object, ...) ## Default S3 method: penalty( object, rescale = FALSE, data, knots = NULL, constraints = FALSE, diagonalize = FALSE, margins = FALSE, ... ) ## S3 method for class 'gam' penalty( object, select = NULL, smooth = deprecated(), rescale = FALSE, partial_match = FALSE, margins = FALSE, ... ) ## S3 method for class 'mgcv.smooth' penalty(object, rescale = FALSE, ...) ## S3 method for class 'tensor.smooth' penalty(object, margins = FALSE, rescale = FALSE, ...) ## S3 method for class 't2.smooth' penalty(object, margins = FALSE, rescale = FALSE, ...) ## S3 method for class 're.smooth.spec' penalty(object, data, rescale = FALSE, margins = FALSE, ...) ## S3 method for class 'scam' penalty(object, ...)
object |
a fitted GAM or a smooth. |
... |
additional arguments passed to methods. |
rescale |
logical; by default, mgcv will scale the penalty matrix for
better performance in |
data |
data frame; a data frame of values for terms mentioned in the smooth specification. |
knots |
a list or data frame with named components containing
knots locations. Names must match the covariates for which the basis
is required. See |
constraints |
logical; should identifiability constraints be applied to
the smooth basis. See argument |
diagonalize |
logical; if |
margins |
logical; if |
select |
character, logical, or numeric; which smooths to extract
penalties for. If |
smooth |
|
partial_match |
logical; should smooths be selected by partial matches
with |
For SCAM fits, the returned penalties act on the unrestricted
fitting parameters, before scam transforms selected coefficients to impose
positivity. The parameterisation attribute records this distinction.
A 'tibble' (data frame) of class penalty_df inheriting from
tbl_df, with the following components:
.smooth - character; the label mgcv uses to refer to the smooth,
.type - character; the type of smooth,
.penalty - character; the label for the specific penalty. Some smooths
have multiple penalty matrices, so the penalty component identifies the
particular penalty matrix and uses the labelling that mgcv uses
internally,
.row - character; a label of the form fn where n is an integer for
the nth basis function, referencing the columns of the penalty matrix,
.col - character; a label of the form fn where n is an integer for
the nth basis function, referencing the columns of the penalty matrix,
.value - double; the value of the penalty matrix for the combination of
row and col,
The print() method uses base::zapsmall() to turn very small numbers
into 0s for display purposes only; the underlying values of the penalty
matrix or matrices are not changed.
For smooths that are subject to an eigendecomposition (e.g. the default
thin plate regression splines, bs = "tp"), the signs of the eigenvectors
are not defined and as such you can expect differences across systems in
the penalties for such smooths that are system-, OS-, and CPU architecture-
specific.
Gavin L. Simpson
load_mgcv() dat <- data_sim("eg4", n = 400, seed = 42) m <- gam( y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, by = fac, bs = "cr"), data = dat, method = "REML" ) # penalties for all smooths penalty(m) # for a specific smooth penalty(m, select = "s(x2):fac1")load_mgcv() dat <- data_sim("eg4", n = 400, seed = 42) m <- gam( y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, by = fac, bs = "cr"), data = dat, method = "REML" ) # penalties for all smooths penalty(m) # for a specific smooth penalty(m, select = "s(x2):fac1")
Low-level Functions to generate draws from the posterior distribution of model coefficients
Generate posterior draws from a fitted model
## S3 method for class 'gamm4' generate_draws(model, ...) ## S3 method for class 'gamm4' post_draws(model, ...) post_draws(model, ...) ## Default S3 method: post_draws( model, ..., n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, index = NULL, parametrized = TRUE ) generate_draws(model, ...) ## S3 method for class 'gam' generate_draws( model, ..., n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, index = NULL ) ## S3 method for class 'scam' generate_draws(model, ...)## S3 method for class 'gamm4' generate_draws(model, ...) ## S3 method for class 'gamm4' post_draws(model, ...) post_draws(model, ...) ## Default S3 method: post_draws( model, ..., n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, index = NULL, parametrized = TRUE ) generate_draws(model, ...) ## S3 method for class 'gam' generate_draws( model, ..., n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, index = NULL ) ## S3 method for class 'scam' generate_draws(model, ...)
model |
a fitted model from |
... |
arguments passed to methods. |
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
chains |
positive integer or |
seed |
numeric or |
method |
character; which algorithm to use to sample from the posterior.
Currently implemented methods are: |
n_cores |
positive integer; maximum concurrent MH chains using mirai,
capped at |
n_threads |
positive integer; threads within Gaussian sampling using mvnfast. Defaults to one. This is separate from concurrent MH chains. |
burnin |
numeric; the length of any initial burn in period to discard.
See |
thin |
positive integer; retain every |
t_df |
numeric; degrees of freedom for static multivariate t proposal.
See |
rw_scale |
numeric; factor by which to scale posterior covariance
matrix when generating random walk proposals. See |
frequentist |
logical; if |
unconditional |
logical; if |
draws |
matrix; user supplied posterior draws to be used when
|
diagnostics |
logical; calculate coefficient R-hat, effective sample sizes, and Monte Carlo standard errors using the optional posterior package. |
mh_backend |
character; |
mvn_method |
character; one of |
block_size |
positive integer; maximum observation rows per block in the gratia MH evaluator. Large designs are evaluated without storing a full matrix. |
dense_limit |
numeric; maximum number of design-matrix elements to cache for the gratia MH backend. Use zero to force blockwise evaluation. |
index |
numeric; vector of indices of coefficients to use. Can be used
to subset the mean vector and covariance matrix extracted from |
parametrized |
logical; for SCAM fits, transform Gaussian draws from
the unrestricted fitting coefficients using the fitted positivity transform.
This preserves the smooth's constraints. With |
Sampling controls must be named. Removed arguments produce migration errors;
see vignette("sampling-migration"). Explicit controls that the selected
method cannot use are rejected.
For SCAM models, Gaussian draws approximate the distribution of the unrestricted
fitting coefficients using Vp (or Ve with frequentist = TRUE), then apply
scam's fitted exponential or notExp transformation. This is an approximation
in fitting coordinates, rather than an exact constrained posterior. Supplied
draws must already use the transformed coordinates in coef(model) order.
Numerically singular covariance matrices are sampled by eigen decomposition;
negative eigenvalues within 100 * .Machine$double.eps * ncol(V) times the
largest absolute eigenvalue are treated as zero. Larger negatives are errors.
For weakly identified exponential coefficients, a very large fitting-coordinate
variance can yield non-finite transformed draws. Sampling then reports an
error because this Gaussian approximation cannot provide usable draws; supply
finite transformed draws from a suitable alternative sampler.
For multiple chains, n_draws is the total retained count and must be divisible
by chains. Coefficient matrices carry a chain mapping; use
as_mcmc_draws() before ordinary matrix operations remove that mapping.
Higher-level sampling tables include .chain and .iteration for multiple
chains, with .draw unique across chains. Default single-chain table columns
are unchanged. Use sampling_diagnostics() to extract coefficient diagnostics
before response simulation adds further noise.
The gratia MH backend supports Gaussian identity, Poisson log, binomial
logit, Gamma log, and negative binomial log fits. It evaluates the fitted
bases at original covariates, including for discrete bam fits. GAMM components, AR1 dependence,
paraPen, H, and fits made from pre-fit G objects are unsupported.
The family MH backend calls the fitted family's dev.resids() and linkinv()
functions, or ll() for families with multiple linear predictors. This
retains response encodings and attributes such as censoring indicators and
the mappings between coefficients and predictors. It supports compatible
standard, extended, and general mgcv families, including multinomial, Gaussian
location-scale, and grouped families. Quasi families, Cox proportional hazards
models, GAMM components, AR1 dependence, paraPen, H, and pre-fit G objects
are unsupported. The fitted coefficient covariance must be nonsingular.
It always caches the full design matrix; block_size and dense_limit apply
only to the gratia backend and are rejected for the family backend.
The new MH backends reject bam fits with nonzero prescribed smooth
contributions: mgcv fitting and prediction can use different offsets for
those fits. Supplied coefficient draws can still be evaluated with the
native prediction conventions.
All MH backends sample the conditional coefficient posterior with fitted
smoothing, dispersion, and additional family parameters fixed. Parameters
represented in the fitted coefficient vector are sampled, including scale
or covariance coefficients in general families. unconditional applies
to Gaussian draws only.
GAM-class fits with linear inequality constraints, including
mgcv::scasm() fits, store these as Ain %*% coefficients >= bin.
Gaussian sampling uses the fitted covariance matrix without enforcing
these inequalities and issues a warning. Sampled smooths can therefore
violate the fitted shape constraints. Pointwise intervals computed from
the same Gaussian covariance approximation also need not preserve those
shapes. All MH backends are unavailable for these fits because
the samplers do not enforce their inequalities.
If mgcv::scasm() was fitted with bs > 0, its bs component stores
coefficient draws from the native constrained bootstrap in columns. These
can be supplied explicitly as draws = t(model$bs) with method = "user".
The result then describes bootstrap variation, rather than Gaussian
posterior sampling. Gratia does not automatically select these draws.
The caller is responsible for the interpretation and constraint
feasibility of user-supplied draws.
Compare the observed response distribution with replicated data sets drawn from the approximate posterior predictive distribution of a fitted model.
posterior_predictive_plot( model, n = 50, seed = NULL, observed_col = "#D55E00", replicated_col = "#0072B2", replicated_alpha = NULL, xlab = NULL, ylab = NULL, title = "Posterior predictive check", subtitle = NULL, caption = NULL, level = 0.9, conditioning = NULL, scalable = NULL, scalable_threshold = 10000L, batch_size = 10L, ..., response = NULL )posterior_predictive_plot( model, n = 50, seed = NULL, observed_col = "#D55E00", replicated_col = "#0072B2", replicated_alpha = NULL, xlab = NULL, ylab = NULL, title = "Posterior predictive check", subtitle = NULL, caption = NULL, level = 0.9, conditioning = NULL, scalable = NULL, scalable_threshold = 10000L, batch_size = 10L, ..., response = NULL )
model |
a fitted model with a posterior response sampler. |
n |
positive integer; number of replicated data sets to draw. |
seed |
numeric; optional random seed. With an explicit seed, the caller's random-number state is preserved. |
observed_col, replicated_col
|
Deprecated; use |
replicated_alpha |
Deprecated; use |
xlab |
character or expression; label for the response axis. |
ylab |
character or expression; the label for the y axis. If not supplied, a suitable label will be generated. |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
level |
numeric; coverage of the equal-tailed posterior predictive
intervals for discrete responses. Must be strictly between zero and one.
Defaults to |
conditioning |
character or |
scalable |
logical or |
scalable_threshold |
positive integer; observation count for automatic scalable plotting. |
batch_size |
positive integer; number of draws per processing batch. Batch boundaries do not alter seeded draws. Scalable discrete comparisons with more than 512 distinct response values aggregate probability into 512 shared equal-width bins to bound memory and plot size. |
... |
arguments passed to |
response |
For |
Mixed-model captions name the conditioning mode. Supply caption to replace this text, or
caption = "" to omit it.
Each replicated data set includes uncertainty in the coefficients and random variation in the responses, at the covariate values used to fit the model. Linear models and GLMs draw coefficients from a Gaussian distribution with the estimated coefficient covariance, keeping dispersion at its fitted value. For GAMs that model several distribution parameters, all their coefficients are drawn together. Distribution parameters outside this coefficient vector remain at fitted values, including additional parameters of grouped-family components.
glmmTMB draws mean, zero-inflation and dispersion coefficients together with
fitted random effects, using a Gaussian (Laplace) approximation to their
posterior. Their covariance includes uncertainty from estimating the
parameters that control random-effect covariance. For conditional checks,
responses are generated using the drawn values of the fitted random effects.
Given those values, their prior covariance is not needed to generate responses.
Additional family parameters, such as Tweedie power, remain at fitted values.
For marginal checks, coefficient draws include the same estimation uncertainty,
but new random effects are generated using the fitted prior covariance. Thus
these checks keep the covariance of new effects fixed while retaining its
estimation uncertainty in the coefficient draws; they do not condition the
coefficient posterior on fixed covariance parameters.
sdmTMB draws parameters together from a Gaussian approximation, including
fixed coefficients and random fields, and uses sdmTMB's response simulator
to generate the complete response. These plots do not require an analytic
residual distribution, so native simulated families such as Student-t and
beta-binomial are available.
SCAM models support ordinary and scalable predictive checks using transformed
coefficient draws. Gaussian identity-link AR1 fits retain the fitted response
correlation and the series boundaries stored in AR.start.
Gaussian gamm and gamm4 models draw fixed and random effects together,
keeping covariance parameters at fitted values; marginal checks draw new
effects.
For gamm fits estimated by penalized quasi-likelihood (PQL), the sampler uses
the Gaussian approximation used in fitting and then generates responses from
the fitted response family. This is supported only when the Gaussian working
residuals are uncorrelated. Correlation in those working residuals does not
specify a joint distribution for responses from the fitted family.
gamm4 defaults to conditioning = "conditional", checking the full fitted
mixed model while including uncertainty in fitted effects. Use the explicit
"gam_component" option for the extracted GAM calculations. GJRM draws the final
distributional coefficients jointly for supported uncensored univariate
families, including BE, LO, WEI, IG, GU and rGU. Both distributional equations
retain their coefficient covariance; beta scale draws use its logit link.
See diagnostic_support for the family list. These are approximate predictive
checks; no refitting is performed.
Continuous responses use kernel density estimates with a common bandwidth
derived from the observed responses and a shared evaluation grid. Discrete
responses show observed empirical probability masses as points, alongside
posterior medians and equal-tailed intervals across replicated data sets.
Observed points, predicted points and intervals are placed at the actual
response values on the horizontal axis. Binomial
responses are compared as proportions, including models fitted to success
and failure counts. Each fitting observation contributes equally to the
empirical distribution. Response sampling follows the fitted family's
interpretation of weights; see posterior_samples(). Factor-valued binomial
observations retain one Bernoulli trial per observation, and native gaulss
fitting weights do not change its response precision. Explicit GAM sampling
weights override the defaults.
Multivariate normal responses are shown in separate facets.
Excluded observations are omitted from both observed and replicated data.
Responses remain on the scale used in fitting, including transformations in
the response formula. Grouped families use separate component facets.
Censored responses require a model of how censoring changes the generated
observations and are not supported. Unsupported models or samplers produce
an error; no alternative simulation method is substituted. Additional sampler limitations are
described in posterior_samples().
A ggplot object. Its data contain the observed responses
(.draw = 0) and posterior replicates (.draw > 0), indexed by .row
and .parameter. Scalable plots instead retain density or probability
summaries evaluated on the same grid for all draws.
appraise(), posterior_samples()
load_mgcv() dat <- data_sim("eg1", n = 100, seed = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML" ) posterior_predictive_plot(mod, n = 20, seed = 42) appraise(mod, ppcheck = TRUE, n_ppc = 20, seed = 42)load_mgcv() dat <- data_sim("eg1", n = 100, seed = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML" ) posterior_predictive_plot(mod, n = 20, seed = 42) appraise(mod, ppcheck = TRUE, n_ppc = 20, seed = 42)
Draw samples from the posterior distribution of an estimated model
## S3 method for class 'lm' posterior_samples(model, ..., n_draws = NULL, seed = NULL) ## S3 method for class 'glm' posterior_samples(model, ..., n_draws = NULL, seed = NULL) ## S3 method for class 'glmmTMB' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'sdmTMB' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'gamlss' posterior_samples(model, ..., n_draws = NULL, seed = NULL) ## S3 method for class 'gamm' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'lme' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'merMod' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'gamm4' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) posterior_samples(model, ...) ## S3 method for class 'gam' posterior_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, weights = NULL, family_index = NULL, marginalise = NULL ) ## S3 method for class 'scam' posterior_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, weights = NULL, family_index = NULL )## S3 method for class 'lm' posterior_samples(model, ..., n_draws = NULL, seed = NULL) ## S3 method for class 'glm' posterior_samples(model, ..., n_draws = NULL, seed = NULL) ## S3 method for class 'glmmTMB' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'sdmTMB' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'gamlss' posterior_samples(model, ..., n_draws = NULL, seed = NULL) ## S3 method for class 'gamm' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'lme' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'merMod' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) ## S3 method for class 'gamm4' posterior_samples(model, ..., n_draws = NULL, seed = NULL, conditioning = NULL) posterior_samples(model, ...) ## S3 method for class 'gam' posterior_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, weights = NULL, family_index = NULL, marginalise = NULL ) ## S3 method for class 'scam' posterior_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, weights = NULL, family_index = NULL )
model |
a fitted model of the supported types; see diagnostic_support. |
... |
arguments passed to other methods. For |
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
seed |
numeric; a random seed for the simulations. |
conditioning |
character or |
data |
data frame; new observations at which the posterior draws
from the model should be evaluated. If not supplied, the data used to fit
the model will be used for |
chains |
positive integer or |
method |
character; which method should be used to draw samples from
the posterior distribution. |
n_cores |
positive integer; maximum concurrent MH chains using mirai,
capped at |
n_threads |
positive integer; threads within Gaussian sampling using mvnfast. Defaults to one. This is separate from concurrent MH chains. |
burnin |
numeric; number of samples to discard as the burnin draws.
Only used with |
thin |
positive integer; retain every |
t_df |
numeric; degrees of freedom for t distribution proposals. Only
used with |
rw_scale |
numeric; Factor by which to scale posterior covariance
matrix when generating random walk proposals. Negative or non finite to
skip the random walk step. Only used with |
frequentist |
logical; |
unconditional |
logical; if |
draws |
matrix; user supplied posterior draws to be used when
|
diagnostics |
logical; calculate coefficient R-hat, effective sample sizes, and Monte Carlo standard errors using the optional posterior package. |
mh_backend |
character; |
mvn_method |
character; one of |
block_size |
positive integer; maximum observation rows per block in the gratia MH evaluator. Large designs are evaluated without storing a full matrix. |
dense_limit |
numeric; maximum number of design-matrix elements to cache for the gratia MH backend. Use zero to force blockwise evaluation. |
weights |
numeric; response sampling weights for GAM methods. An
explicit vector overrides the fitting weights; a single value applies to
every observation. With |
family_index |
numeric; optional family-list positions for grouped
family ( |
marginalise |
|
The lm, glm, glmmTMB, GJRM::gamlss, sdmTMB, and full mixed-model
diagnostic samplers currently use the fitting observations only. They draw
coefficients together using Gaussian approximations. See
posterior_predictive_plot() for which additional distribution parameters
remain fixed and how random effects are treated for each fitter.
With no explicit data, observation rows follow the fitted model's
na.action. na.exclude restores excluded rows as NA in every draw;
na.omit returns retained rows only. .row indexes the fitting data after
any subset. With explicit data, .row indexes that data, missing
responses do not prevent prediction, and missing required predictors give
NA draws. An explicit prediction na.action in ... is honoured without
renumbering retained rows. Restoration does not consume random numbers.
For Gaussian identity-link bam and scam fits, first-order autoregressive (AR1) errors
make consecutive responses correlated. Responses are drawn together to retain
this fitted correlation, restarting at each AR.start segment. These draws
currently use the fitting observations only. For other families or links,
the AR1 correction applies to working residuals used during fitting. It does
not specify a joint distribution of actual responses, so sampling produces
an error.
Location-scale-shape families mgcv::gaulss(), mgcv::gammals(),
mgcv::gumbls(), mgcv::gevlss(), mgcv::shash(), mgcv::twlss() and
mgcv::ziplss() support fitting observations, subsets and new covariates.
Every distribution parameter is computed from the same joint coefficient
draw. Formula offsets and prescribed smooth contributions are retained.
Evaluation data need predictors and formula-offset variables, but no
observed response. mgcv natively represents the second gaulss() parameter
as reciprocal standard deviation: response sampling uses SD, divided by the square
root of the sampling weight. Other LSS generators currently ignore sampling
weights, following their mgcv implementations. Parameters represented by
coefficients vary jointly; other family parameters remain fixed.
Cox survival models require evaluation times and an observation process and
do not have a response generator for this interface. Censored-family draws
are latent, uncensored responses; reproducing observed censoring requires
an observation process and remains unsupported in posterior predictive checks.
Grouped-family posterior response draws support fitting observations and
supplied data with known family membership. Component nuisance parameters
remain fixed. .parameter identifies the component used for each row.
Censored grouped components require an observation process; use simulate()
for their latent, uncensored responses.
With marginalise, selected random effects are drawn for new groups in
each response replicate. Group labels must be supplied for new data.
See random_effect_samples() for the estimated Gaussian distributions.
A tibble (data frame) in long format, with columns:
.row: row of the evaluation data;
.draw: globally unique draw identifier;
.response: simulated response.
Where needed, .parameter identifies the response or grouped component.
Multiple-chain output also includes .chain and .iteration. Attached
coefficient diagnostics are available through sampling_diagnostics().
With data = NULL, fitting offsets are retained, including offsets
supplied through the fitting function's offset argument. Explicit prediction
data follow mgcv::predict.gam(): offsets in formulas are evaluated from
the prediction data, while offsets supplied through the fitting function's
offset argument are not transferred to new observations. Include offsets
in the formula when predicting at new data; the required offset variables
must then be present in data.
Gavin L. Simpson
Wood, S.N., (2020). Simplified integrated nested Laplace approximation. Biometrika 107, 223–230. doi:10.1093/biomet/asz044
Compare observations with replicated responses using an optional installation
of bayesplot. Call bayesplot::pp_check() after loading gratia.
pp_check.gam( object, ..., type = "dens_overlay", prefix = c("ppc", "ppd"), n_draws = NULL, seed = NULL, group = NULL, x = NULL, response = NULL, conditioning = NULL, sampling_args = list() ) pp_check.bam( object, ..., type = "dens_overlay", prefix = c("ppc", "ppd"), n_draws = NULL, seed = NULL, group = NULL, x = NULL, response = NULL, conditioning = NULL, sampling_args = list() ) pp_check.gamm( object, ..., type = "dens_overlay", prefix = c("ppc", "ppd"), n_draws = NULL, seed = NULL, group = NULL, x = NULL, response = NULL, conditioning = NULL, sampling_args = list() ) pp_check.gamm4( object, ..., type = "dens_overlay", prefix = c("ppc", "ppd"), n_draws = NULL, seed = NULL, group = NULL, x = NULL, response = NULL, conditioning = NULL, sampling_args = list() ) pp_check.scam(object, ...)pp_check.gam( object, ..., type = "dens_overlay", prefix = c("ppc", "ppd"), n_draws = NULL, seed = NULL, group = NULL, x = NULL, response = NULL, conditioning = NULL, sampling_args = list() ) pp_check.bam( object, ..., type = "dens_overlay", prefix = c("ppc", "ppd"), n_draws = NULL, seed = NULL, group = NULL, x = NULL, response = NULL, conditioning = NULL, sampling_args = list() ) pp_check.gamm( object, ..., type = "dens_overlay", prefix = c("ppc", "ppd"), n_draws = NULL, seed = NULL, group = NULL, x = NULL, response = NULL, conditioning = NULL, sampling_args = list() ) pp_check.gamm4( object, ..., type = "dens_overlay", prefix = c("ppc", "ppd"), n_draws = NULL, seed = NULL, group = NULL, x = NULL, response = NULL, conditioning = NULL, sampling_args = list() ) pp_check.scam(object, ...)
object |
a fitted GAM, BAM, gamm, or gamm4 model. |
... |
arguments passed only to the selected bayesplot plotting function. |
type |
character; the bayesplot plot name without its |
prefix |
character; |
n_draws |
positive integer; total coefficient and response draws. Defaults to 50 for ordinary plots and 4000 for leave-one-out plots. With supplied coefficient draws, defaults to their number of rows. |
seed |
integer or |
group, x
|
a variable name in the fitting model frame, or a vector in fitting-row order. Missing fitting rows are removed with the response. |
response |
character or integer; response column or grouped-family
component to check, for example |
conditioning |
character or |
sampling_args |
named list; arguments for the posterior sampler, including
|
These methods require bayesplot only when called. Leave-one-out plots also
require loo and a likelihood supported by log_lik(). Their response and
likelihood calculations use exactly the same coefficient draws. For a
multivariate response, the weights leave out the entire response vector.
Grouped-family checks use only the selected component's observations.
Some bayesplot plotting functions, including error_binned and LOO-PIT
plots, also require bayesplot's optional rstantools package. Install it with
install.packages("rstantools") to use those plots.
Binomial observations and replicated responses are shown as numbers of
successes with fitted trial counts. Other gratia predictive plots use
proportions. The error_binned plot uses expected responses rather than
response simulations and requires an available finite response mean. For
gamm and gamm4 it currently requires conditioning = "gam_component".
Plotting functions requiring additional inputs, such
as censoring indicators, receive those inputs through ....
Coefficient draws use a Gaussian approximation by default; additional family
parameters remain at fitted values. See log_lik() for the assumptions of
approximate leave-one-out calculations. Existing conditioning and response
dependence restrictions of the diagnostic samplers also apply here.
The object returned by the selected bayesplot function, usually a ggplot object.
posterior_predictive_plot(), log_lik()
if (requireNamespace("bayesplot", quietly = TRUE)) { load_mgcv() dat <- data_sim("eg1", n = 100, seed = 2) fit <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat) bayesplot::pp_check(fit, n_draws = 10, seed = 42) }if (requireNamespace("bayesplot", quietly = TRUE)) { load_mgcv() dat <- data_sim("eg1", n = 100, seed = 2) fit <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat) bayesplot::pp_check(fit, n_draws = 10, seed = 42) }
Predicted values of the response (new response data) are drawn from the
fitted model, created via simulate() (e.g. simulate.gam()) and returned
in a tidy, long, format. These predicted values do not include the
uncertainty in the estimated model; they are simply draws from the
conditional distribution of the response.
## S3 method for class 'gamm4' predicted_samples(model, ...) predicted_samples(model, ...) ## Default S3 method: predicted_samples(model, ...) ## S3 method for class 'gam' predicted_samples( model, ..., data = NULL, n_draws = NULL, seed = NULL, weights = NULL, marginalise = NULL ) ## S3 method for class 'scam' predicted_samples( model, ..., data = NULL, n_draws = NULL, seed = NULL, weights = NULL )## S3 method for class 'gamm4' predicted_samples(model, ...) predicted_samples(model, ...) ## Default S3 method: predicted_samples(model, ...) ## S3 method for class 'gam' predicted_samples( model, ..., data = NULL, n_draws = NULL, seed = NULL, weights = NULL, marginalise = NULL ) ## S3 method for class 'scam' predicted_samples( model, ..., data = NULL, n_draws = NULL, seed = NULL, weights = NULL )
model |
a fitted model of the supported types; see diagnostic_support. |
... |
arguments passed to other methods. For |
data |
data frame; new observations at which the posterior draws
from the model should be evaluated. If not supplied, the data used to fit
the model will be used for |
n_draws |
positive integer; number of response replicates to generate at the fitted parameters. Required; coefficient chains are not used. |
seed |
numeric; a random seed for the simulations. |
weights |
numeric; response sampling weights for GAM methods. An
explicit vector overrides the fitting weights; a single value applies to
every observation. With |
marginalise |
|
LSS response simulation uses all fitted distribution parameters at the
requested data, with the same parameter transformations and offset rules as
posterior_samples(). It holds coefficients fixed, so it has no coefficient
chains or attached coefficient diagnostics.
A tibble (data frame) with 3 columns containing the posterior predicted values in long format. The columns are
.row (integer) the row of data that each posterior draw relates to,
.draw (integer) an index, in range 1:n_draws, indicating which draw each row
relates to,
.response (numeric) the predicted response for the indicated row of
data.
Gavin L. Simpson
load_mgcv() dat <- data_sim("eg1", n = 1000, dist = "normal", scale = 2, seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") predicted_samples(m, n_draws = 5, seed = 42) ## Can pass arguments to predict.gam() newd <- data.frame( x0 = runif(10), x1 = runif(10), x2 = runif(10), x3 = runif(10) ) ## Exclude s(x2) predicted_samples(m, n_draws = 5, data = newd, exclude = "s(x2)", seed = 25) ## Exclude s(x1) predicted_samples(m, n_draws = 5, data = newd, exclude = "s(x1)", seed = 25) ## Select which terms --- result should be the same as previous ## but note that we have to include any parametric terms, including the ## constant term predicted_samples(m, n_draws = 5, data = newd, seed = 25, terms = c("Intercept", "s(x0)", "s(x2)", "s(x3)") )load_mgcv() dat <- data_sim("eg1", n = 1000, dist = "normal", scale = 2, seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") predicted_samples(m, n_draws = 5, seed = 42) ## Can pass arguments to predict.gam() newd <- data.frame( x0 = runif(10), x1 = runif(10), x2 = runif(10), x3 = runif(10) ) ## Exclude s(x2) predicted_samples(m, n_draws = 5, data = newd, exclude = "s(x2)", seed = 25) ## Exclude s(x1) predicted_samples(m, n_draws = 5, data = newd, exclude = "s(x1)", seed = 25) ## Select which terms --- result should be the same as previous ## but note that we have to include any parametric terms, including the ## constant term predicted_samples(m, n_draws = 5, data = newd, seed = 25, terms = c("Intercept", "s(x0)", "s(x2)", "s(x3)") )
Quantile-quantile plots (QQ plots) for fitted models using the reference quantiles of Augustin et al (2012), or fixed normal references for randomised quantile residuals following Dunn and Smyth (1996).
qq_plot(model, ...) ## Default S3 method: qq_plot(model, ...) ## S3 method for class 'gam' qq_plot( model, method = NULL, type = NULL, n_uniform = 10, n_simulate = 50, seed = NULL, level = 0.9, ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, ci_col = "black", ci_alpha = 0.2, point_col = "grey20", point_alpha = 1, line_col = "red", by_family = NULL, conditioning = NULL, ..., n_dharma = 250L ) ## S3 method for class 'glm' qq_plot(model, ...) ## S3 method for class 'lm' qq_plot(model, ...) ## S3 method for class 'gamm4' qq_plot(model, conditioning = NULL, ...) ## S3 method for class 'gjrm' qq_plot(model, ..., type = "quantile", seed = NULL, response = NULL) ## S3 method for class 'gamm' qq_plot(model, conditioning = NULL, ...) ## S3 method for class 'gratia_diagnostic_proxy' qq_plot(model, type = "quantile", ...) ## S3 method for class 'lme' qq_plot(model, conditioning = NULL, ...) ## S3 method for class 'merMod' qq_plot(model, conditioning = NULL, ...) ## S3 method for class 'gamlss' qq_plot(model, ..., type = "quantile", seed = NULL) ## S3 method for class 'sdmTMB' qq_plot( model, conditioning = NULL, component = "response", field_method = c("mle-mvn", "mle-eb", "mle-mvn-integrated"), ... )qq_plot(model, ...) ## Default S3 method: qq_plot(model, ...) ## S3 method for class 'gam' qq_plot( model, method = NULL, type = NULL, n_uniform = 10, n_simulate = 50, seed = NULL, level = 0.9, ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, ci_col = "black", ci_alpha = 0.2, point_col = "grey20", point_alpha = 1, line_col = "red", by_family = NULL, conditioning = NULL, ..., n_dharma = 250L ) ## S3 method for class 'glm' qq_plot(model, ...) ## S3 method for class 'lm' qq_plot(model, ...) ## S3 method for class 'gamm4' qq_plot(model, conditioning = NULL, ...) ## S3 method for class 'gjrm' qq_plot(model, ..., type = "quantile", seed = NULL, response = NULL) ## S3 method for class 'gamm' qq_plot(model, conditioning = NULL, ...) ## S3 method for class 'gratia_diagnostic_proxy' qq_plot(model, type = "quantile", ...) ## S3 method for class 'lme' qq_plot(model, conditioning = NULL, ...) ## S3 method for class 'merMod' qq_plot(model, conditioning = NULL, ...) ## S3 method for class 'gamlss' qq_plot(model, ..., type = "quantile", seed = NULL) ## S3 method for class 'sdmTMB' qq_plot( model, conditioning = NULL, component = "response", field_method = c("mle-mvn", "mle-eb", "mle-mvn-integrated"), ... )
model |
a fitted model supported by diagnostic_support. |
... |
arguments passed to other methods. |
method |
character or
For ordinary GAMs, |
type |
character or |
n_uniform |
numeric; number of inverse-CDF draws to average when
|
n_simulate |
numeric; number of data sets to simulate from the estimated
model when using the simulation method ( |
seed |
numeric; the random number seed to use for |
level |
numeric; the coverage level for reference intervals. Must be
strictly |
ylab |
character or expression; the label for the y axis. If not supplied, a suitable label will be generated. |
xlab |
character or expression; the label for the x axis. If not supplied, a suitable label will be generated. |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
ci_col |
Deprecated; use |
ci_alpha |
Deprecated; use |
point_col |
Deprecated; use |
point_alpha |
Deprecated; use |
line_col |
Deprecated; use |
by_family |
logical or |
conditioning |
character or |
n_dharma |
positive integer; number of response simulations for
|
response |
|
component |
character; for delta sdmTMB models, select the complete
|
field_method |
how to treat fitted sdmTMB fields: hold one posterior
draw fixed ( |
See appraise() for grouped-family defaults, supported distributions,
pooling and separate component panels. PIT and quantile residuals use fixed
uniform and standard-normal reference quantiles. For ideal independent
responses, bands are pointwise intervals for ordered residuals. For dependent
responses, bands use simulations that preserve dependence when available;
otherwise they are omitted. Residuals calculated from simulation ranks also
use simulated bands. See diagnostic_support for these choices and limits.
Bands condition on fitted parameters and exclude fitting uncertainty; they
do not provide simultaneous coverage. Traditional residuals use the fitted
response distributions or a normal approximation.
For mgcv::ocat() fits, type = "surrogate" uses logistic reference
quantiles with location zero and scale one. Set method = NULL. Independent
observations have approximate pointwise bands obtained by applying
qlogis() to beta order-statistic limits. Worm plots subtract the same
logistic reference quantiles from residuals and bands. These references
treat fitted parameters as fixed. For mgcv::multinom() GAMs, surrogate
residuals retain a utility component for every category, including 0.
Components have separate facets and centred Gumbel reference quantiles,
including when by_family = FALSE. The same reference is subtracted in
worm plots, and pointwise beta order-statistic bands use the centred
Gumbel quantile function separately for each component. Ordinary and
scalable displays share their draw. See surrogate_residuals().
Subtitles name the method. Captions identify conditioning and field choices,
joint simulation bands or omitted bands. Routine pointwise bands are unlabelled.
Supply caption to replace this text, or caption = "" to omit it.
Ordinary and scalable QQ and worm plots use the same labels.
The wording used in mgcv::qq.gam() uses direct in reference to the
simulated residuals method (method = "simulated"). To avoid confusion,
method = "direct" is deprecated in favour of method = "uniform".
The underlying methodology used when method is "simulate" or "uniform"
is described in Augustin et al (2012):
Dunn, P.K. and Smyth, G.K. (1996) Randomized quantile residuals. Journal of Computational and Graphical Statistics 5, 236–244.
Augustin, N.H., Sauleau, E.-A., Wood, S.N., (2012) On quantile quantile plots for generalized linear models. Computational Statistics and Data Analysis 56, 2404-2409 doi:10.1016/j.csda.2012.01.026.
mgcv::qq.gam for more details on the methods used.
load_mgcv() ## simulate binomial data... dat <- data_sim("eg1", n = 200, dist = "binary", scale = .33, seed = 0) p <- binomial()$linkinv(dat$f) # binomial p n <- sample(c(1, 3), 200, replace = TRUE) # binomial n dat <- transform(dat, y = rbinom(n, n, p), n = n) m <- gam(y / n ~ s(x0) + s(x1) + s(x2) + s(x3), family = binomial, data = dat, weights = n, method = "REML" ) ## Q-Q plot; default using direct randomization of uniform quantiles qq_plot(m) ## Alternatively simulate new data from the model, which ## allows construction of reference intervals for the Q-Q plot qq_plot(m, method = "simulate", seed = 42, point_col = "steelblue", point_alpha = 0.4 ) ## ... or request a normal approximation for the residuals. qq_plot(m, method = "normal")load_mgcv() ## simulate binomial data... dat <- data_sim("eg1", n = 200, dist = "binary", scale = .33, seed = 0) p <- binomial()$linkinv(dat$f) # binomial p n <- sample(c(1, 3), 200, replace = TRUE) # binomial n dat <- transform(dat, y = rbinom(n, n, p), n = n) m <- gam(y / n ~ s(x0) + s(x1) + s(x2) + s(x3), family = binomial, data = dat, weights = n, method = "REML" ) ## Q-Q plot; default using direct randomization of uniform quantiles qq_plot(m) ## Alternatively simulate new data from the model, which ## allows construction of reference intervals for the Q-Q plot qq_plot(m, method = "simulate", seed = 42, point_col = "steelblue", point_alpha = 0.4 ) ## ... or request a normal approximation for the residuals. qq_plot(m, method = "normal")
Evaluate and plot the stored mgcv smooths in a glmmTMB fit. Coefficients and their joint covariance are transformed back to the constrained mgcv basis. Intervals use TMB's joint covariance, including fixed–random covariance; they are not mgcv frequentist or smoothness-corrected intervals.
## S3 method for class 'glmmTMB' qq_plot(model, ..., method = NULL, type = NULL, conditioning = NULL) ## S3 method for class 'glmmTMB' worm_plot(model, ..., method = NULL, type = NULL, conditioning = NULL) ## S3 method for class 'glmmTMB' appraise(model, ..., method = NULL, type = NULL, conditioning = NULL) ## S3 method for class 'glmmTMB' parametric_terms(model, ...) ## S3 method for class 'glmmTMB' parametric_effects( object, terms = NULL, ..., unconditional = FALSE, frequentist = FALSE ) ## S3 method for class 'glmmTMB' smooths(object, ...) ## S3 method for class 'glmmTMB' get_smooths_by_id(object, id, ...) ## S3 method for class 'glmmTMB' smooth_estimates(object, ..., unconditional = FALSE, frequentist = FALSE) ## S3 method for class 'glmmTMB' smooth_coefs(object, select, ...) ## S3 method for class 'glmmTMB' assemble( object, ..., parametric = NULL, residuals = FALSE, unconditional = FALSE, frequentist = FALSE, ranef_lines = FALSE, envir = NULL ) ## S3 method for class 'glmmTMB' draw( object, ..., parametric = NULL, residuals = FALSE, unconditional = FALSE, frequentist = FALSE, ranef_lines = FALSE, envir = NULL )## S3 method for class 'glmmTMB' qq_plot(model, ..., method = NULL, type = NULL, conditioning = NULL) ## S3 method for class 'glmmTMB' worm_plot(model, ..., method = NULL, type = NULL, conditioning = NULL) ## S3 method for class 'glmmTMB' appraise(model, ..., method = NULL, type = NULL, conditioning = NULL) ## S3 method for class 'glmmTMB' parametric_terms(model, ...) ## S3 method for class 'glmmTMB' parametric_effects( object, terms = NULL, ..., unconditional = FALSE, frequentist = FALSE ) ## S3 method for class 'glmmTMB' smooths(object, ...) ## S3 method for class 'glmmTMB' get_smooths_by_id(object, id, ...) ## S3 method for class 'glmmTMB' smooth_estimates(object, ..., unconditional = FALSE, frequentist = FALSE) ## S3 method for class 'glmmTMB' smooth_coefs(object, select, ...) ## S3 method for class 'glmmTMB' assemble( object, ..., parametric = NULL, residuals = FALSE, unconditional = FALSE, frequentist = FALSE, ranef_lines = FALSE, envir = NULL ) ## S3 method for class 'glmmTMB' draw( object, ..., parametric = NULL, residuals = FALSE, unconditional = FALSE, frequentist = FALSE, ranef_lines = FALSE, envir = NULL )
... |
Arguments passed to the corresponding gratia method. |
method |
QQ method; |
type |
Residual type: |
conditioning |
character or |
object, model
|
A fitted |
terms |
Character vector selecting parametric terms, as returned by
|
unconditional, frequentist
|
Must be |
id |
Integer positions of smooths across all linear predictors. |
select |
Smooth or native random-effect coefficient selection, across
all linear predictors. Numeric indices select smooths first, then native
random coefficients. Native labels have the form |
parametric |
Include parametric effect plots? |
residuals |
Must be |
ranef_lines |
Logical; replace QQ plots for a simple native random
intercept and numeric slope term, |
envir |
Optional environment for evaluating model covariates. |
Smooth support requires stored smooth and random-effect metadata. Unsupported
multi-penalty structures, mapped joint parameters and rank-deficient smooth
models give errors. Factor-by and tensor smooth availability is determined
by glmmTMB; gratia does not expand the smooth types glmmTMB can fit.
Use draw(model, surface = "3d", ci_3d = TRUE) for interval surfaces on
smooths and numeric parametric interactions in any linear predictor.
ci_3d_alpha and ci_3d_col control their opacity and fill colour.
Pass cyclic = "polar" and optional polar_args to draw() or
assemble() for polar plots of supported one-dimensional cyclic smooths.
See draw.gam() for the coordinate options.
Parametric effects use fitted contrast coding and exclude smooth null-space
coefficients. Their intervals include uncertainty in the intercept of their
own linear predictor by default, as for GAMs. overall_uncertainty = FALSE
gives term-only intervals. Models without smooths are also supported.
Native random effects use one Gaussian QQ panel per coefficient type and
grouping factor, matching mgcv random-effect smooth plots. The internal
random effects representing smooths are excluded from these panels.
With ranef_lines = TRUE, eligible intercept-slope pairs use a common grid
over the fitting range of the numeric covariate, or its supplied data
values. Lines show random contributions only, without population-level
terms or uncertainty bands. Different formula terms are never combined.
Diagnostics use native Pearson residuals by default. QQ simulations hold
fitted smooths and grouping effects fixed and draw new responses; no refitting
is performed. Supported response families are Gaussian, Poisson, binomial,
nbinom1/2, beta, Gamma/ziGamma, Tweedie, lognormal, and zero-truncated
Poisson/nbinom1/2,
including applicable zero-inflation or hurdle mixtures and varying dispersion.
Truncated nbinom1 currently requires type = "response" because glmmTMB
does not supply its Pearson residuals. Other unavailable residual types fail
explicitly. Supported fitted response distributions also provide randomized
PIT/quantile residuals and inverse-CDF QQ references, including their
zero-inflation and truncation probabilities. Posterior predictive checks draw
coefficients and fitted random effects together from their approximate
posterior. See posterior_predictive_plot() for how covariance and other
family parameters are treated. Marginal checks simulate new effects using
glmmTMB's response generator. If marginal CDFs are not analytic, residual
checks use a shared sample of simulations to calculate moments and ranks.
See diagnostic_support for conditioning choices and remaining limitations.
Smooth estimates, coefficients, or plots, as for the GAM methods.
assemble() returns a named list of ggplot objects, of class
"assembled_plots". draw() combines these plots into a patchwork unless
wrap = FALSE, which returns the individual plots instead.
All smooths, native random effects and parametric terms are plotted by
default, as for draw.gam(). Smooths in later
linear predictors use mgcv-style labels such as s.1(x) and s.2(x).
Predictor order is conditional, zero-inflation (if present), then dispersion
(if present). Use smooths(object) and select to select individual smooths.
For models with multiple linear predictors, smooth and parametric subtitles
identify the "Conditional model", "Zero-inflation model" or "Dispersion model",
consistently with native random-effect panels. Constant dispersion alone
does not trigger these subtitles.
Saved parametric_effects() retain the labels in an optional .model column.
names(assemble(object, parametric = FALSE)) also lists native
random-effect coefficient panels.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
if (requireNamespace("glmmTMB", quietly = TRUE)) { load_mgcv() # Simulate a nonlinear mean with Gaussian noise set.seed(42) d <- data.frame(x = runif(150)) d$y <- sin(6 * d$x) + rnorm(150, sd = 0.2) # Fit and draw a smooth using glmmTMB m <- glmmTMB::glmmTMB(y ~ s(x, k = 8), data = d, REML = TRUE) n_smooths(m) draw(m) }if (requireNamespace("glmmTMB", quietly = TRUE)) { load_mgcv() # Simulate a nonlinear mean with Gaussian noise set.seed(42) d <- data.frame(x = runif(150)) d$y <- sin(6 * d$x) + rnorm(150, sd = 0.2) # Fit and draw a smooth using glmmTMB m <- glmmTMB::glmmTMB(y ~ s(x, k = 8), data = d, REML = TRUE) n_smooths(m) draw(m) }
Map observations to probabilities under the fitted response distribution. These probability integral transform (PIT) residuals have a uniform reference distribution under a correctly specified continuous model with known parameters. Quantile residuals transform them to standard-normal scores. Discrete observations require randomisation over their probability mass.
## S3 method for class 'gamm4' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'gamlss' quantile_residuals(model, type = c("pit", "quantile"), seed = NULL, ...) ## S3 method for class 'gjrm' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, response = NULL, ... ) ## S3 method for class 'gamm' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'gratia_diagnostic_proxy' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'lme' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'merMod' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, ..., response = NULL ) ## S3 method for class 'gam' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ..., response = NULL ) ## S3 method for class 'glm' quantile_residuals(model, type = c("pit", "quantile"), seed = NULL, ...) ## S3 method for class 'lm' quantile_residuals(model, type = c("pit", "quantile"), seed = NULL, ...) ## Default S3 method: quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'glmmTMB' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'gratia_glmmtmb_diagnostic' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'sdmTMB' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, component = "response", field_method = c("mle-mvn", "mle-eb", "mle-mvn-integrated"), ... )## S3 method for class 'gamm4' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'gamlss' quantile_residuals(model, type = c("pit", "quantile"), seed = NULL, ...) ## S3 method for class 'gjrm' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, response = NULL, ... ) ## S3 method for class 'gamm' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'gratia_diagnostic_proxy' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'lme' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'merMod' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, ..., response = NULL ) ## S3 method for class 'gam' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ..., response = NULL ) ## S3 method for class 'glm' quantile_residuals(model, type = c("pit", "quantile"), seed = NULL, ...) ## S3 method for class 'lm' quantile_residuals(model, type = c("pit", "quantile"), seed = NULL, ...) ## Default S3 method: quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'glmmTMB' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'gratia_glmmtmb_diagnostic' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, ... ) ## S3 method for class 'sdmTMB' quantile_residuals( model, type = c("pit", "quantile"), seed = NULL, conditioning = NULL, component = "response", field_method = c("mle-mvn", "mle-eb", "mle-mvn-integrated"), ... )
model |
a fitted model object. |
type |
character; |
seed |
integer or |
conditioning |
character or |
... |
arguments passed to other methods. |
response |
|
component |
character; which delta sdmTMB component to check; see
|
field_method |
For sdmTMB diagnostics,
|
With na.exclude, excluded observations are restored as NA residuals;
with na.omit, only observations used for fitting are returned. Selecting a
grouped-family component with response returns only its retained fitting
observations, without placeholders for excluded rows whose component
membership is unavailable.
For mgcv::cnorm(), mgcv::clog() and mgcv::cpois() models, censored
observations have PIT residuals sampled uniformly between F(l) and F(u).
Here l and u bound the censoring interval and F is the fitted cumulative
distribution function (CDF) of the underlying response. Left and right
censoring use probabilities zero and one for the unbounded end, respectively.
Quantile residuals apply qnorm() to these PIT values. Uncensored continuous
observations use F(y); uncensored Poisson observations are randomised between
F(y - 1) and F(y). Use non-integer censoring limits for cpois(), as
recommended by mgcv.
For grouped-family GAMs fitted with mgcv::gfam(), each observation uses its
component's CDF, fitted nuisance parameters, dispersion and weights. Residuals
are returned in fitting order. response = NULL uses all components; an
integer selects observations assigned to that family-list position. Repeated
families retain distinct indices. With an explicit seed, selected residuals
match the corresponding rows of an all-component call whenever all
components support the calculation. All selected active components must supply supported
CDFs and probability limits for discrete or censored observations. Unsupported
components give an error; appraise() can instead select deviance residuals
automatically. See appraise() for supported families. Tweedie zeros have
positive probability mass: their PITs are randomised between F(0-) = 0 and
F(0). Positive observations use F(y).
When a CDF can calculate log probabilities in both tails, quantile residuals
use the log probability in the smaller tail directly. This avoids infinities
caused by rounding probabilities to zero or one. Probabilities are not
clipped, so true zero-probability tails still give infinite residuals for
ordinary models; grouped diagnostics report non-finite residuals as errors.
PITs are returned as ordinary probabilities and may still round to zero or
one in extreme tails. Applying qnorm() to returned PITs can therefore be
less accurate than requesting quantile residuals directly. CDFs without log
probabilities retain ordinary-probability calculations.
For mgcv::multinom() models, probabilities accumulate in the existing
category coding order 0, ..., K. If category j has probability p_j,
its PIT is F(j - 1) + V * p_j, where V is uniform on (0, 1).
This uses one categorical response, rather than a vector of trial counts.
The coding does not change the multinomial likelihood into an ordinal model.
Each fixed enumeration gives a uniform randomized transform under the true
model, but changing the enumeration can change individual residuals and
which departures from the model are easiest to detect.
Marginal checks may calculate residuals from ranks in joint response simulations when no analytic marginal CDF is available. See diagnostic_support for the rank definition, conditioning choices and limitations after fitting.
Sample zero-mean Gaussian random effects using the fitted smoothing parameters and dispersion. These are new effects, rather than posterior draws of the effects estimated for the fitting groups.
random_effect_samples(model, data = NULL, select = NULL, n_draws, seed = NULL)random_effect_samples(model, data = NULL, select = NULL, n_draws, seed = NULL)
model |
An ordinary |
data |
Evaluation data. With |
select |
Exact smooth labels, or |
n_draws |
Positive integer giving the number of draws. |
seed |
Optional integer seed. An explicit seed preserves the caller's
random-number state; |
Standard re random intercepts, slopes and factor interactions, and fs
random curves are supported. Each curve is drawn jointly over its evaluation
points, including the components penalising its constant and linear parts.
Custom re penalties supplied through xt$S are unsupported. Fits using
min.sp are also unsupported: mgcv does not retain the fitted lower bounds
needed to reconstruct their random-effect covariance.
For stored penalties , smoothing parameters , and
dispersion , coefficient covariance is
Smoothing parameters and dispersion remain fixed. As in mgcv::gam.vcomp(),
random-effect covariance uses reml.scale when it is finite and sig2
otherwise. Response generators retain their usual sig2 dispersion.
Different smooths and
different groups have independent new coefficients, as specified by these
model terms. Covariance between fitted coefficients is not used here.
Use marginalise in fitted_values() or fitted_samples() to integrate
response means over these distributions. Use it in predicted_samples(),
posterior_samples() or simulate.gam() to simulate new-group responses.
A tibble of class random_effect_samples, with .row, .draw,
.smooth, .value (the link-scale contribution), and covariates. The
random_effect_info attribute describes the fixed covariance estimates.
load_mgcv() m <- gam(travel ~ s(Rail, bs = "re"), data = nlme::Rail, method = "REML") random_effect_samples(m, n_draws = 3, seed = 42) # Compare zero random effects with response means averaged over groups. set.seed(2) d <- expand.grid(x = seq(0, 1, length.out = 15), id = factor(1:12)) d$y <- rpois(nrow(d), exp(0.3 + d$x + rnorm(12, sd = 0.6)[d$id])) p <- gam(y ~ x + s(id, bs = "re"), data = d, family = poisson(), method = "REML") nd <- data.frame(x = c(0, 0.5, 1), id = d$id[1]) fitted_values(p, data = nd, exclude = "s(id)") fitted_values(p, data = nd, marginalise = TRUE) fitted_values(p, data = nd, marginalise = TRUE, integration = "monte_carlo", seed = 42) nd$id <- c("new", "new", "other") predicted_samples(p, data = nd, marginalise = TRUE, n_draws = 3, seed = 42)load_mgcv() m <- gam(travel ~ s(Rail, bs = "re"), data = nlme::Rail, method = "REML") random_effect_samples(m, n_draws = 3, seed = 42) # Compare zero random effects with response means averaged over groups. set.seed(2) d <- expand.grid(x = seq(0, 1, length.out = 15), id = factor(1:12)) d$y <- rpois(nrow(d), exp(0.3 + d$x + rnorm(12, sd = 0.6)[d$id])) p <- gam(y ~ x + s(id, bs = "re"), data = d, family = poisson(), method = "REML") nd <- data.frame(x = c(0, 0.5, 1), id = d$id[1]) fitted_values(p, data = nd, exclude = "s(id)") fitted_values(p, data = nd, marginalise = TRUE) fitted_values(p, data = nd, marginalise = TRUE, integration = "monte_carlo", seed = 42) nd$id <- c("new", "new", "other") predicted_samples(p, data = nd, marginalise = TRUE, n_draws = 3, seed = 42)
Extracts the reference or a specific level the supplied factor, returning it as a factor with the same levels as the one supplied.
ref_level(fct) level(fct, level)ref_level(fct) level(fct, level)
fct |
factor; the factor from which the reference or specific level will be extracted. |
level |
character; the specific level to extract in the case of
|
A factor with the selected values and the same levels, level order
and ordered status as fct. ref_level() returns the first level.
f <- factor(sample(letters[1:5], 100, replace = TRUE)) # the reference level ref_level(f) # a specific level level(f, level = "b") # note that the levels will always match the input factor identical(levels(f), levels(ref_level(f))) identical(levels(f), levels(level(f, "c")))f <- factor(sample(letters[1:5], 100, replace = TRUE)) # the reference level ref_level(f) # a specific level level(f, level = "b") # note that the levels will always match the input factor identical(levels(f), levels(ref_level(f))) identical(levels(f), levels(level(f, "c")))
A set of reference objects for testing data_sim().
A named list of simulated data sets created by data_sim().
Function to repeat the first level of a factor n times and return this vector as a factor with the original levels intact
rep_first_factor_value(f, n)rep_first_factor_value(f, n)
f |
a factor |
n |
numeric; the number of times to repeat the first level of |
A factor of length n with the levels of f, but whose elements
are all the first level of f.
Compute lag correlations within independent series. These are descriptive checks of ordered residual structure, with no independence-based confidence bands or significance tests.
residual_correlation( model, type = NULL, lag_max = 20L, series = NULL, seed = NULL, ..., n_dharma = 250L ) residual_correlation_plot( model, type = NULL, lag_max = 20L, series = NULL, seed = NULL, ..., n_dharma = 250L )residual_correlation( model, type = NULL, lag_max = 20L, series = NULL, seed = NULL, ..., n_dharma = 250L ) residual_correlation_plot( model, type = NULL, lag_max = 20L, series = NULL, seed = NULL, ..., n_dharma = 250L )
model |
a supported fitted model. |
type |
residual type. For an AR1 BAM the default is |
lag_max |
positive integer; maximum observation lag. |
series |
optional vector identifying series, in the order of observations
used for fitting or of the original observations. BAM's |
seed |
optional seed for randomized residuals. |
... |
arguments used to prepare the model for diagnostics, including
|
n_dharma |
positive integer; number of response simulations for
|
Use type = "dharma" and n_dharma for simulation-based PIT residuals
on the uniform scale; see dharma_residuals().
Use type = "surrogate" for ocat() models to calculate correlations of
residuals on the latent logistic scale; see surrogate_residuals().
BAM's generalized estimating equations (GEE) AR1 correction acts on the
weighted working response used for fitting. Whitening
these working residuals can reveal remaining serial structure. The stored
std.rsd in current mgcv adjusts its final residuals for AR1 correlation,
which need not be the weighted working residuals for non-Gaussian models.
Both checks are approximate. They can reveal remaining serial structure, but
do not specify a joint response distribution, establish normality or provide
calibrated goodness-of-fit tests.
Fitted parameters, leverage and discrete likelihoods affect correlations.
Lags use observation positions within series, not elapsed time or spatial
distance. Means are removed within each series, and correlations use only
finite pairs at each lag; missing residuals and omitted fitting rows do not
close gaps. If series are interleaved, supply series for all original
observations so omitted rows can be assigned to the right series. If series
covers only observations used for fitting, an omitted position is counted
as a gap in every series with observations on both sides of it. Observations
assigned to another series never create gaps. Significance bands that assume
independent residuals are omitted. Check spatial
residual patterns with their coordinates and a suitable distance diagnostic.
residual_correlation() returns a tibble with lag, correlation and
the number of finite observation pairs used at each lag. residual_correlation_plot() returns a ggplot.
Inspect residuals from the complete fitted model against individual covariates or pairs of numeric covariates.
residuals_covariate_plot( model, covariates = NULL, terms = NULL, pairs = NULL, data = NULL, by = NULL, type = NULL, smooth = NULL, bins = c(20L, 20L), min_n = 5L, statistic = c("mean", "sd"), seed = NULL, conditioning = NULL, n_dharma = 250L, point_col = "grey20", point_alpha = 0.5, line_col = "red", xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ncol = NULL, ... ) scalable_residuals_covariate_plot( model, covariates = NULL, terms = NULL, pairs = NULL, data = NULL, by = NULL, type = NULL, smooth = NULL, bins = c(20L, 20L), min_n = 5L, statistic = c("mean", "sd"), seed = NULL, conditioning = NULL, n_dharma = 250L, density_bins = c(50L, 50L), density = c("conditional", "count"), density_method = c("kde", "histogram"), bandwidth = NULL, line_col = "red", xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ncol = NULL, ... )residuals_covariate_plot( model, covariates = NULL, terms = NULL, pairs = NULL, data = NULL, by = NULL, type = NULL, smooth = NULL, bins = c(20L, 20L), min_n = 5L, statistic = c("mean", "sd"), seed = NULL, conditioning = NULL, n_dharma = 250L, point_col = "grey20", point_alpha = 0.5, line_col = "red", xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ncol = NULL, ... ) scalable_residuals_covariate_plot( model, covariates = NULL, terms = NULL, pairs = NULL, data = NULL, by = NULL, type = NULL, smooth = NULL, bins = c(20L, 20L), min_n = 5L, statistic = c("mean", "sd"), seed = NULL, conditioning = NULL, n_dharma = 250L, density_bins = c(50L, 50L), density = c("conditional", "count"), density_method = c("kde", "histogram"), bandwidth = NULL, line_col = "red", xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ncol = NULL, ... )
model |
a fitted model supported by diagnostic_support, or prepared diagnostic data. The original model must retain its fitting observations. |
covariates |
character vector of exact covariate names, in plotting
order. |
terms |
character vector of exact mgcv smooth labels, as returned by
|
pairs |
list of character vectors, each naming two distinct numeric covariates. Adds a joint residual map for each pair, in the supplied order. |
data |
original fitting data or retained fitting observations, including
model predictors needed to verify alignment. Can contain additional
covariates absent from the model. Rows are matched to stored observations
and their evaluated predictors checked. Row counts alone do not establish
alignment. |
by |
optional name of a categorical covariate defining separate facets. |
type |
character or |
smooth |
logical or |
bins |
positive integer or pair of integers giving the numbers of cells along the two covariate axes of joint maps. |
min_n |
positive integer; joint-map cells with fewer observations are blank. Counts for occupied cells are retained in the plotting data. |
statistic |
joint-map summary: |
seed |
integer; random seed to use for PIT, quantile, surrogate or DHARMa-style residuals. |
conditioning |
character or |
n_dharma |
positive integer; number of simulations for DHARMa residuals. |
point_col |
Deprecated; use |
point_alpha |
Deprecated; use |
line_col |
Deprecated; use |
xlab |
character or expression; the label for the x axis. If not supplied, a suitable label will be generated. |
ylab |
character or expression; the label for the y axis. If not supplied, a suitable label will be generated. |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
ncol |
optional number of columns when composing several panels. |
... |
arguments used to prepare model diagnostics, such as sdmTMB
|
density_bins |
Positive integer or pair of integers giving the number of horizontal and vertical heatmap bins. |
density |
One of |
density_method |
Conditional-density estimator: |
bandwidth |
Optional pair of positive bandwidths for the predictor and
residual axes, in their plotted units. |
Covariates are plotted in their original units. A term such as s(log(x))
selects x; stored transformed coordinates are never inverted to recover
original values. Supply data if those values are unavailable. Term
selection does not plot fitted term contributions or partial residuals. A
factor-specific smooth selects covariates without restricting observations;
use by to inspect patterns separately among groups.
Pearson residuals are useful for checking the mean function because they account for the specified mean–variance relationship. Response residuals retain the response units. A remaining curve can suggest an incorrectly specified mean function, including insufficient flexibility in a smooth. Quantile and PIT residuals are useful for checking the conditional response distribution, including changing spread and tails. Non-Gaussian deviance residuals need not have zero conditional mean, so their mean curve need not follow the zero reference line even under the fitted model.
Numeric panels show points, or conditional-density heatmaps in the scalable version. Categorical panels show boxplots and group means; the ordinary version also shows points. Joint maps show means or standard deviations within rectangular cells. The ordinary version also shows observation locations. Mean maps use a diverging colour scale centred on zero, or 0.5 for PIT and DHARMa residuals. Standard-deviation maps use a sequential scale. These are descriptive summaries, not tests against simulated reference maps. An omitted interaction can produce a joint pattern even when both individual covariate panels appear flat. Correlated covariates can share residual patterns; use the plots to guide model revisions and subsequent checks.
All eligible observations are used. Mean trends use a shrinkage cubic spline
with up to 40 basis functions, fitted with GCV below 10,000 observations and
discrete fREML via mgcv::bam() otherwise. The same calculation is used by
both plotting functions. Trends are omitted with fewer than four distinct
covariate values. Summaries and trends are calculated separately within each
response, family component and by group. Missing plotting values are
reported and omitted separately for each requested plot.
A ggplot for one panel, or a patchwork composition for several. Scalable plots retain only summaries and evaluated trend curves.
appraise(), residuals_linpred_plot(), partial_residuals()
load_mgcv() dat <- data_sim("eg1", n = 400, seed = 2) m <- gam(y ~ x2 + s(x0) + s(x1), data = dat, method = "REML") # A curve against x2 suggests reconsidering its linear effect. residuals_covariate_plot(m, covariates = "x2", type = "pearson") # Check a covariate omitted from the model. residuals_covariate_plot(m, covariates = "x3", data = dat) # Inspect individual covariates and possible remaining interaction structure. scalable_residuals_covariate_plot(m, covariates = c("x0", "x2"), pairs = list(c("x0", "x2")), bins = 6, type = "quantile", seed = 42)load_mgcv() dat <- data_sim("eg1", n = 400, seed = 2) m <- gam(y ~ x2 + s(x0) + s(x1), data = dat, method = "REML") # A curve against x2 suggests reconsidering its linear effect. residuals_covariate_plot(m, covariates = "x2", type = "pearson") # Check a covariate omitted from the model. residuals_covariate_plot(m, covariates = "x3", data = dat) # Inspect individual covariates and possible remaining interaction structure. scalable_residuals_covariate_plot(m, covariates = c("x0", "x2"), pairs = list(c("x0", "x2")), bins = 6, type = "quantile", seed = 42)
Histogram of model residuals
residuals_hist_plot( model, type = NULL, n_bins = c("sturges", "scott", "fd"), ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, seed = NULL, by_family = NULL, conditioning = NULL, ..., n_dharma = 250L )residuals_hist_plot( model, type = NULL, n_bins = c("sturges", "scott", "fd"), ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, seed = NULL, by_family = NULL, conditioning = NULL, ..., n_dharma = 250L )
model |
a fitted model supported by diagnostic_support. |
type |
character or |
n_bins |
character or numeric; either the number of bins or a string indicating how to calculate the number of bins. |
ylab |
character or expression; the label for the y axis. If not supplied, a suitable label will be generated. |
xlab |
character or expression; the label for the x axis. If not supplied, a suitable label will be generated. |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
seed |
integer; random seed to use for PIT, quantile, surrogate or DHARMa-style residuals. |
by_family |
logical or |
conditioning |
character or |
... |
optional arguments passed to model preparation, such as the
sdmTMB |
n_dharma |
positive integer; number of response simulations for
|
Pooled grouped-family histograms use common bin edges and
component-specific densities, with faint group-coloured fills and opaque
stepped upper boundaries. Set by_family = TRUE for separate panels.
Plot of residuals versus linear predictor values
residuals_linpred_plot( model, type = NULL, ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, point_col = "grey20", point_alpha = 1, line_col = "red", seed = NULL, by_family = NULL, rank = NULL, conditioning = NULL, ..., n_dharma = 250L )residuals_linpred_plot( model, type = NULL, ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, point_col = "grey20", point_alpha = 1, line_col = "red", seed = NULL, by_family = NULL, rank = NULL, conditioning = NULL, ..., n_dharma = 250L )
model |
a fitted model supported by diagnostic_support. |
type |
character or |
ylab |
character or expression; the label for the y axis. If not supplied, a suitable label will be generated. |
xlab |
character or expression; the label for the x axis. If not supplied, a suitable label will be generated. |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
point_col |
Deprecated; use |
point_alpha |
Deprecated; use |
line_col |
Deprecated; use |
seed |
integer; random seed to use for PIT, quantile, surrogate or DHARMa-style residuals. |
by_family |
logical or |
rank |
logical or |
conditioning |
character or |
... |
optional arguments passed to model preparation, such as the
sdmTMB |
n_dharma |
positive integer; number of response simulations for
|
The default subtitle identifies the response family. Conditioning
and field choices appear in the caption where relevant. Supply caption
to replace this text, or caption = "" to omit it. The scalable version
uses the same labels.
Derivatives on the response scale from an estimated GAM
response_derivatives(object, ...) ## Default S3 method: response_derivatives(object, ...) ## S3 method for class 'gamm' response_derivatives(object, ...) ## S3 method for class 'gam' response_derivatives( object, focal = NULL, data = NULL, order = 1L, type = c("forward", "backward", "central"), scale = c("response", "linear_predictor"), method = c("gaussian", "mh", "inla", "user"), n = 100, eps = NULL, n_sim = 10000, level = 0.95, seed = NULL, mvn_method = c("mvnfast", "mgcv"), ..., uncertainty = c("simulation", "delta"), unconditional = FALSE ) ## S3 method for class 'scam' response_derivatives( object, focal = NULL, data = NULL, order = 1L, type = c("forward", "backward", "central"), scale = c("response", "linear_predictor"), method = c("gaussian", "mh", "inla", "user"), n = 100, eps = NULL, n_sim = 10000, level = 0.95, seed = NULL, mvn_method = c("mvnfast", "mgcv"), ..., uncertainty = c("simulation", "delta"), unconditional = FALSE ) ## S3 method for class 'gamm4' response_derivatives(object, ...)response_derivatives(object, ...) ## Default S3 method: response_derivatives(object, ...) ## S3 method for class 'gamm' response_derivatives(object, ...) ## S3 method for class 'gam' response_derivatives( object, focal = NULL, data = NULL, order = 1L, type = c("forward", "backward", "central"), scale = c("response", "linear_predictor"), method = c("gaussian", "mh", "inla", "user"), n = 100, eps = NULL, n_sim = 10000, level = 0.95, seed = NULL, mvn_method = c("mvnfast", "mgcv"), ..., uncertainty = c("simulation", "delta"), unconditional = FALSE ) ## S3 method for class 'scam' response_derivatives( object, focal = NULL, data = NULL, order = 1L, type = c("forward", "backward", "central"), scale = c("response", "linear_predictor"), method = c("gaussian", "mh", "inla", "user"), n = 100, eps = NULL, n_sim = 10000, level = 0.95, seed = NULL, mvn_method = c("mvnfast", "mgcv"), ..., uncertainty = c("simulation", "delta"), unconditional = FALSE ) ## S3 method for class 'gamm4' response_derivatives(object, ...)
object |
an R object to compute derivatives for. |
... |
arguments passed to posterior sampling or prediction, such as
|
focal |
character; name of the focal variable. The response derivative of the response with respect to this variable will be returned. All other variables involved in the model will be held at constant values. This must be supplied. |
data |
a data frame containing the values of the model covariates at which to evaluate derivatives of fitted values. If supplied, all but one variable must be held at a constant value. |
order |
numeric; the order of derivative. |
type |
character; the type of finite difference used. One of
|
scale |
character; should the derivative be estimated on the response
or the linear predictor (link) scale? One of |
method |
character; which method should be used to draw samples from
the posterior distribution. |
n |
numeric; the number of points to evaluate the derivative at (if
|
eps |
a positive finite number giving the absolute finite-difference
step, or |
n_sim |
integer; number of posterior draws. Ignored when using user-supplied draws. |
level |
numeric; |
seed |
numeric; a random seed for the simulations. |
mvn_method |
character; one of |
uncertainty |
character; |
unconditional |
logical; include smoothing-parameter uncertainty in the Bayesian covariance, if available, for delta intervals and Gaussian draws. This does not modify MH or user-supplied draws. |
Delta uncertainty uses the same shifted prediction rows and finite-difference formulas as simulation, for both first and second derivatives. It applies those formulas to the coefficient gradients of fitted means and propagates their full joint covariance. Formula offsets are included in predictions. Intervals concern derivatives of the conditional mean, not future observations. With Bayesian coefficient covariance, delta intervals have an approximate posterior interpretation. They are symmetric and may differ from simulation intervals when posterior transformations are strongly nonlinear; the two methods' point estimates can also differ.
Delta uncertainty supports single-linear-predictor gam and bam models
with an ordinary scalar inverse-link mean (including negative binomial,
Tweedie, beta regression, and scaled t families), and gamm via its GAM
component. SCAM models use transformed-coefficient covariance conditional on
the fitted smoothing parameters. General multi-predictor families do not
support delta uncertainty; their existing simulation support is unchanged.
The uncertainty attribute records the selected method.
By default, all supplied prediction rows are returned in their original
order. Rows with missing or non-finite required covariates have NA
derivatives, standard errors and interval limits. Category, response and
family identifiers are retained. An explicit na.action follows the
prediction convention: na.omit drops unavailable rows with missing
covariates, na.exclude and na.pass retain them, and na.fail reports
missing covariates as an error. Undefined calculations at available rows,
including in only some coefficient draws, raise an error; draws are never
removed to form a summary.
Response-scale derivatives require the expected response to exist. For a scaled t family, fitted degrees of freedom must exceed one, whether fixed or estimated. A finite response variance is not required. Linear-predictor derivatives remain available when the response mean does not exist.
A tibble, currently with the following variables:
.row: integer, indexing the row of data each row in the output
represents
.focal: the name of the variable for which the partial derivative was
evaluated,
.derivative: the posterior median for simulation uncertainty, or the
finite difference of fitted predictions for delta uncertainty,
.se: posterior standard deviation for simulation uncertainty (NA with
only one draw), or the delta-method standard error,
.lower_ci: the lower bound of the pointwise interval,
.upper_ci: the upper bound of the pointwise interval,
additional columns containing the covariate values at which the derivative was evaluated.
Gavin L. Simpson
library("ggplot2") library("patchwork") load_mgcv() df <- data_sim("eg1", dist = "negbin", scale = 0.25, seed = 42) # fit the GAM (note: for execution time reasons using bam()) m <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, family = nb(), method = "fREML" ) # data slice through data along x2 - all other covariates will be set to # typical values (value closest to median) ds <- data_slice(m, x2 = evenly(x2, n = 100)) # fitted values along x2 fv <- fitted_values(m, data = ds) # response derivatives - ideally n_sim = >10000 y_d <- response_derivatives(m, data = ds, type = "central", focal = "x2", eps = 0.01, seed = 21, n_sim = 1000 ) # draw fitted values along x2 p1 <- fv |> ggplot(aes(x = x2, y = .fitted)) + geom_ribbon(aes(ymin = .lower_ci, ymax = .upper_ci, y = NULL), alpha = 0.2 ) + geom_line() + labs( title = "Estimated count as a function of x2", y = "Estimated count" ) # pointwise normal intervals from the delta method y_delta <- response_derivatives(m, data = ds, focal = "x2", type = "central", uncertainty = "delta") # draw response derivatives p2 <- y_d |> ggplot(aes(x = x2, y = .derivative)) + geom_ribbon(aes(ymin = .lower_ci, ymax = .upper_ci), alpha = 0.2) + geom_line() + labs( title = "Estimated 1st derivative of estimated count", y = "First derivative" ) # draw both panels p1 + p2 + plot_layout(nrow = 2)library("ggplot2") library("patchwork") load_mgcv() df <- data_sim("eg1", dist = "negbin", scale = 0.25, seed = 42) # fit the GAM (note: for execution time reasons using bam()) m <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, family = nb(), method = "fREML" ) # data slice through data along x2 - all other covariates will be set to # typical values (value closest to median) ds <- data_slice(m, x2 = evenly(x2, n = 100)) # fitted values along x2 fv <- fitted_values(m, data = ds) # response derivatives - ideally n_sim = >10000 y_d <- response_derivatives(m, data = ds, type = "central", focal = "x2", eps = 0.01, seed = 21, n_sim = 1000 ) # draw fitted values along x2 p1 <- fv |> ggplot(aes(x = x2, y = .fitted)) + geom_ribbon(aes(ymin = .lower_ci, ymax = .upper_ci, y = NULL), alpha = 0.2 ) + geom_line() + labs( title = "Estimated count as a function of x2", y = "Estimated count" ) # pointwise normal intervals from the delta method y_delta <- response_derivatives(m, data = ds, focal = "x2", type = "central", uncertainty = "delta") # draw response derivatives p2 <- y_d |> ggplot(aes(x = x2, y = .derivative)) + geom_ribbon(aes(ymin = .lower_ci, ymax = .upper_ci), alpha = 0.2) + geom_line() + labs( title = "Estimated 1st derivative of estimated count", y = "First derivative" ) # draw both panels p1 + p2 + plot_layout(nrow = 2)
A rootogram is a model diagnostic tool that assesses the goodness of fit of
a statistical model. The observed values of the response are compared with
those expected from the fitted model. For discrete, count responses, the
frequency of each count (0, 1, 2, etc) in the observed data and expected
from the conditional distribution of the response implied by the model are
compared. For continuous variables, the observed and expected frequencies
are obtained by grouping the data into bins. The rootogram is drawn using
ggplot2::ggplot() graphics. The design closely follows Kleiber & Zeileis
(2016).
## S3 method for class 'gamm4' rootogram(object, ..., conditioning = NULL) rootogram(object, ...) ## S3 method for class 'gam' rootogram(object, max_count = NULL, breaks = "Sturges", ...) ## S3 method for class 'scam' rootogram(object, ...)## S3 method for class 'gamm4' rootogram(object, ..., conditioning = NULL) rootogram(object, ...) ## S3 method for class 'gam' rootogram(object, max_count = NULL, breaks = "Sturges", ...) ## S3 method for class 'scam' rootogram(object, ...)
object |
an R object |
... |
arguments passed to other methods |
conditioning |
for gamm4, |
max_count |
integer; the largest count to consider |
breaks |
for continuous responses, how to group the response. Can be
anything that is acceptable as the |
Kleiber, C., Zeileis, A., (2016) Visualizing Count Data Regressions Using Rootograms. Am. Stat. 70, 296–303. doi:10.1080/00031305.2016.1173590
load_mgcv() df <- data_sim("eg1", n = 1000, dist = "poisson", scale = 0.1, seed = 6) # A poisson example m <- gam(y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, bs = "cr") + s(x3, bs = "cr"), family = poisson(), data = df, method = "REML") rg <- rootogram(m) rg draw(rg) # plot the rootogram # A Gaussian example df <- data_sim("eg1", dist = "normal", seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") draw(rootogram(m, breaks = "FD"), type = "suspended")load_mgcv() df <- data_sim("eg1", n = 1000, dist = "poisson", scale = 0.1, seed = 6) # A poisson example m <- gam(y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, bs = "cr") + s(x3, bs = "cr"), family = poisson(), data = df, method = "REML") rg <- rootogram(m) rg draw(rg) # plot the rootogram # A Gaussian example df <- data_sim("eg1", dist = "normal", seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") draw(rootogram(m, breaks = "FD"), type = "suspended")
Simulate random deviates from a Tweedie distribution with given parameters
, , and . Works with vector values for
all parameters, unlike the version on mgcv.
rtw(mu, p, phi)rtw(mu, p, phi)
mu |
numeric vector of mean values of Tweedie distribution. |
p |
numeric vector of values for the power parameter of the Tweedie distribution. |
phi |
numeric vector of values for the scale parameter |
Parameters must be finite numeric vectors of length one or a common nonzero length. Length-one parameters are expanded to the common length; partial recycling is not supported. If all parameters are empty, an empty numeric vector is returned; mixing empty and nonempty parameters is an error.
Diagnostics attached to fitted values or response samples describe the
coefficient chains before transformation or response simulation. Response
noise can conceal poor mixing of coefficient chains. Use as_mcmc_draws()
to examine particular derived quantities as well.
sampling_diagnostics(x) ## S3 method for class 'sampling_diagnostics' print(x, ...)sampling_diagnostics(x) ## S3 method for class 'sampling_diagnostics' print(x, ...)
x |
Output from a gratia sampling function; for the print method, a
|
... |
Further arguments passed to the print methods for the summaries. |
Coefficient draws are retained when sampling with diagnostics = TRUE,
allowing draw.sampling_diagnostics() to plot the original coefficient
chains even when x contains response samples, fitted values, smooths or
derivatives. These plots do not describe the transformed quantities.
Numerical summaries require posterior, but plotting does not.
A sampling_diagnostics list with chains (acceptance rates and
elapsed seconds), coefficients (posterior summaries, or NULL if not
requested), and draws (a coefficient matrix with chain identities, or
NULL if unavailable). Coefficient matrices provide their own draws;
other sampling outputs need diagnostics = TRUE to retain them.
Likelihood matrices from log_lik() also require diagnostics = TRUE
for coefficient plots; use as_mcmc_draws() for their log-density draws.
draw.sampling_diagnostics(), as_mcmc_draws()
Aggregate all observations before drawing model diagnostic plots with ggplot. QQ points are grouped into bins of equal distance along the curve, keeping both endpoints. Heatmaps and histograms contain precomputed counts, so redrawing does not bin the original data again. Uniform references average draws as they are generated. Simulated references retain exact pooled quantiles, using temporary files above the configured memory threshold; see diagnostic_support.
scalable_qq_plot( model, method = NULL, type = NULL, n_uniform = 10, n_simulate = 50, seed = NULL, level = 0.9, qq_bins = 1000L, xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ci_col = "black", ci_alpha = 0.2, point_col = "grey20", point_alpha = 1, line_col = "red", by_family = NULL, conditioning = NULL, ..., n_dharma = 250L ) scalable_worm_plot(model, ..., n_dharma = 250L) scalable_residuals_linpred_plot( model, type = NULL, density_bins = c(50L, 50L), density = c("conditional", "count"), seed = NULL, xlab = NULL, ylab = NULL, title = "Residuals vs linear predictor", subtitle = NULL, caption = NULL, line_col = "red", by_family = NULL, rank = NULL, density_method = c("kde", "histogram"), bandwidth = NULL, conditioning = NULL, ..., n_dharma = 250L ) scalable_observed_fitted_plot( model, density_bins = c(50L, 50L), density = c("count", "conditional"), xlab = "Fitted values", ylab = "Response", title = "Observed vs fitted values", subtitle = NULL, caption = NULL, by_family = NULL, conditioning = NULL, ... ) scalable_residuals_hist_plot( model, type = NULL, n_bins = c("sturges", "scott", "fd"), seed = NULL, xlab = NULL, ylab = "Frequency", title = "Histogram of residuals", subtitle = NULL, caption = NULL, by_family = NULL, conditioning = NULL, ..., n_dharma = 250L )scalable_qq_plot( model, method = NULL, type = NULL, n_uniform = 10, n_simulate = 50, seed = NULL, level = 0.9, qq_bins = 1000L, xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, caption = NULL, ci_col = "black", ci_alpha = 0.2, point_col = "grey20", point_alpha = 1, line_col = "red", by_family = NULL, conditioning = NULL, ..., n_dharma = 250L ) scalable_worm_plot(model, ..., n_dharma = 250L) scalable_residuals_linpred_plot( model, type = NULL, density_bins = c(50L, 50L), density = c("conditional", "count"), seed = NULL, xlab = NULL, ylab = NULL, title = "Residuals vs linear predictor", subtitle = NULL, caption = NULL, line_col = "red", by_family = NULL, rank = NULL, density_method = c("kde", "histogram"), bandwidth = NULL, conditioning = NULL, ..., n_dharma = 250L ) scalable_observed_fitted_plot( model, density_bins = c(50L, 50L), density = c("count", "conditional"), xlab = "Fitted values", ylab = "Response", title = "Observed vs fitted values", subtitle = NULL, caption = NULL, by_family = NULL, conditioning = NULL, ... ) scalable_residuals_hist_plot( model, type = NULL, n_bins = c("sturges", "scott", "fd"), seed = NULL, xlab = NULL, ylab = "Frequency", title = "Histogram of residuals", subtitle = NULL, caption = NULL, by_family = NULL, conditioning = NULL, ..., n_dharma = 250L )
model |
A fitted model supported by diagnostic_support. |
method |
character or
For ordinary GAMs, |
type |
Residual type; |
n_uniform |
numeric; number of inverse-CDF draws to average when
|
n_simulate |
numeric; number of data sets to simulate from the estimated
model when using the simulation method ( |
seed |
Random seed for QQ calculations or randomized residuals. Explicit seeds preserve the caller's RNG state, including an absent state. |
level |
Coverage of pointwise QQ reference intervals, strictly between zero and one. Used by simulation and normal-reference methods. |
qq_bins |
Maximum number of QQ points per family component, including both endpoints; an integer of at least three. |
xlab, ylab
|
Axis labels; |
title, subtitle, caption
|
Plot title, subtitle and caption, passed to
|
ci_col |
Deprecated; use |
ci_alpha |
Deprecated; use |
point_col |
Deprecated; use |
point_alpha |
Deprecated; use |
line_col |
Deprecated; use |
by_family |
logical or |
conditioning |
character or |
... |
optional arguments used to prepare the model for diagnostics,
including sdmTMB |
n_dharma |
positive integer; number of response simulations for
|
density_bins |
Positive integer or pair of integers giving the number of horizontal and vertical heatmap bins. |
density |
One of |
rank |
logical or |
density_method |
Conditional-density estimator: |
bandwidth |
Optional pair of positive bandwidths for the predictor and
residual axes, in their plotted units. |
n_bins |
character or numeric; either the number of bins or a string indicating how to calculate the number of bins. |
GJRM support covers uncensored univariate N, LN, GA, GAi, P, NBI, NBII, BE, LO, WEI, IG, GU and rGU models. PIT/quantile references are uniform/normal; traditional response/Pearson references use inverse-CDF or simulated responses. Probabilities are recomputed from final likelihood parameters. Quantile QQ bands give pointwise intervals for ordered standard-normal residuals, conditional on the fitted distribution, without accounting for parameter estimation. Observed-versus-fitted plots use response means, including the lognormal, Weibull and Gumbel mean corrections. Residuals are plotted against the first distributional linear predictor.
Grouped-family models retain the residual defaults, component reference
distributions, predictor ranks and layout controls of appraise(). QQ
bin limits apply separately to each component. Pooled residual
heatmaps summarize the component mixture rather than colouring individual
observations; observed-versus-fitted appraisals always separate components.
Pooled histograms use faint component-coloured fills with opaque stepped
upper boundaries, retaining common bin edges and component densities.
Residual-versus-predictor plots identify the response family in the subtitle
and show conditioning and field choices in the caption where relevant,
matching residuals_linpred_plot(). Supply caption = "" to omit the caption.
Kernel density estimates are calculated on a fixed grid before plotting.
Each predictor slice is normalized to integrate to one over the displayed
residual grid. Bandwidths, rather than density_bins, control smoothing;
increase grid resolution when using small bandwidths. A square-root fill
transformation reveals low-density regions while retaining density units
in the legend. Gaussian kernels smooth the bands that discrete residuals
can form even under a correctly specified count model. Smoothing does not
give traditional residuals a common reference distribution.
Point styling affects QQ and worm points. Heatmap fill scales can be replaced with ggplot scales. Non-finite plotting observations are reported and omitted; fitting exclusions do not count as dropped observations.
A ggplot object containing aggregated plotting data.
Fasiolo, M., Nedellec, R., Goude, Y. and Wood, S. N. (2020). Scalable Visualization Methods for Modern Generalized Additive Models. Journal of Computational and Graphical Statistics, 29, 78-86. doi:10.1080/10618600.2019.1629942.
appraise(), qq_plot(), worm_plot()
load_mgcv() dat <- data_sim("eg1", n = 400, seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat) scalable_qq_plot(m, seed = 42) scalable_residuals_linpred_plot(m) scalable_observed_fitted_plot(m, density_bins = c(30, 40)) appraise(m, scalable = TRUE, seed = 42)load_mgcv() dat <- data_sim("eg1", n = 400, seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat) scalable_qq_plot(m, seed = 42) scalable_residuals_linpred_plot(m) scalable_observed_fitted_plot(m, density_bins = c(30, 40)) appraise(m, scalable = TRUE, seed = 42)
Default diverging red-blue colour palette for partial effects
scale_fill_partial_effect( name = "Partial effect", ..., na.value = "grey50", guide = "colourbar", direction = -1 )scale_fill_partial_effect( name = "Partial effect", ..., na.value = "grey50", guide = "colourbar", direction = -1 )
name |
The name of the scale. Used as the legend title. If |
... |
arguments passed to |
na.value |
Missing values will be replaced with this value (colour). |
guide |
A function used to create a guide or its name. See
|
direction |
Sets the order of colours in the scale. If |
Evaluate and plot formula smooths and parametric effects from a fitted
sdmTMB model using the same plotting methods as mgcv smooths. Penalized
and unpenalized coefficients and their joint covariance are transformed
back to the constrained mgcv basis.
## S3 method for class 'sdmTMB' smooths(object, ...) ## S3 method for class 'sdmTMB' n_smooths(object) ## S3 method for class 'sdmTMB' get_smooths_by_id(object, id, ...) ## S3 method for class 'sdmTMB' smooth_coefs(object, select, ...) ## S3 method for class 'sdmTMB' smooth_estimates( object, ..., unconditional = FALSE, frequentist = FALSE, envir = NULL ) ## S3 method for class 'sdmTMB' parametric_terms(model, ...) ## S3 method for class 'sdmTMB' parametric_effects( object, terms = NULL, ..., unconditional = FALSE, frequentist = FALSE, envir = NULL ) ## S3 method for class 'sdmTMB' assemble( object, ..., parametric = NULL, residuals = FALSE, unconditional = FALSE, frequentist = FALSE, envir = NULL, time_varying_style = c("ribbon", "pointrange") ) ## S3 method for class 'sdmTMB' draw( object, ..., parametric = NULL, residuals = FALSE, unconditional = FALSE, frequentist = FALSE, envir = NULL, time_varying_style = c("ribbon", "pointrange") )## S3 method for class 'sdmTMB' smooths(object, ...) ## S3 method for class 'sdmTMB' n_smooths(object) ## S3 method for class 'sdmTMB' get_smooths_by_id(object, id, ...) ## S3 method for class 'sdmTMB' smooth_coefs(object, select, ...) ## S3 method for class 'sdmTMB' smooth_estimates( object, ..., unconditional = FALSE, frequentist = FALSE, envir = NULL ) ## S3 method for class 'sdmTMB' parametric_terms(model, ...) ## S3 method for class 'sdmTMB' parametric_effects( object, terms = NULL, ..., unconditional = FALSE, frequentist = FALSE, envir = NULL ) ## S3 method for class 'sdmTMB' assemble( object, ..., parametric = NULL, residuals = FALSE, unconditional = FALSE, frequentist = FALSE, envir = NULL, time_varying_style = c("ribbon", "pointrange") ) ## S3 method for class 'sdmTMB' draw( object, ..., parametric = NULL, residuals = FALSE, unconditional = FALSE, frequentist = FALSE, envir = NULL, time_varying_style = c("ribbon", "pointrange") )
object, model
|
A fitted |
... |
Arguments passed to the corresponding gratia methods, including
grid, interval, transformation, surface, styling and layout controls.
For threshold terms, |
id |
Integer positions of smooths across model components. |
select |
Smooth selection across both predictors of delta models.
Numeric and logical indices follow stored smooth order, first component
then
second. Character selections use |
unconditional, frequentist
|
Must be |
envir |
Optional environment for evaluating model covariates. |
terms |
Parametric terms to evaluate or draw, as returned by
|
parametric |
Include parametric effects? |
residuals |
Must be |
time_varying_style |
Display time-varying coefficients with a line,
points and uncertainty ribbon ( |
Use smooths() to list smooth names, get_smooth() to extract an exact
name, get_smooths_by_id() to extract by position, and n_smooths() to
count smooths, including both predictors of a delta model. These utilities
do not calculate coefficient covariances.
Smooth, ordinary parametric and threshold estimates are partial contributions
on each component's link scale. Spatial, spatiotemporal, IID random effects,
offsets and varying coefficients are not added to these effects. Their
influence on coefficient uncertainty is
retained through the joint covariance. Smooth intervals include uncertainty
in their component's overall mean by default; parametric intervals include
the component's intercept. Use overall_uncertainty = FALSE for term-only
intervals. fun transforms displayed partial effects, not full predictions.
Use surface = "3d", ci_3d = TRUE in draw() or assemble() to add
interval surfaces to smooths and numeric parametric interactions in either
component. ci_3d_alpha and ci_3d_col control their opacity and fill colour.
Pass cyclic = "polar" and optional polar_args to draw() or
assemble() for polar plots of supported one-dimensional cyclic smooths.
See draw.gam() for the coordinate options.
Delta components have separate smooth and parametric coefficients and are
drawn separately, with component subtitles. Upstream sdmTMB restrictions on
supported bases and delta formulas still apply. Tensor smooths with multiple
penalties are supported. Fits require stored smooth metadata; mapping or
profiling required coefficients and non-positive-definite Hessians
give errors.
Parametric subtitles also identify the component for threshold curves and
time-varying coefficients. Saved parametric_effects() retain the labels
in an optional .model column.
Support requires sdmTMB >= 1.2.0 models fitted with the RTMB backend.
Refit older models or TMB fits with
control = sdmTMB::sdmTMBcontrol(backend = "rtmb").
Diagnostics use complete fitted predictors, including spatial, spatiotemporal
and independent group effects and offsets. Supported single-response and standard delta
families provide PIT/quantile residuals, ordinary and scalable diagnostic
plots, and joint approximate posterior predictive checks. Delta diagnostics
can select the complete response, occurrence or positive component. Raw
posterior response draws are available through posterior_samples().
By default, fields are drawn together once from their approximate posterior
and held fixed (mle-mvn), following sdmTMB's recommended residual calculation.
Checks can also hold estimates fixed, average over fitted-field uncertainty,
or simulate new fields. Marginal simulations preserve dependence and supply
residual ranks, including for nonlinear and coupled delta responses. See
diagnostic_support for treatment of coefficients, fields and covariance,
and what each check assesses.
Threshold curves are partial contributions without centring. They follow
parametric selection rules: terms selects them and parametric = FALSE
excludes them. Both delta components have separate threshold parameters.
Threshold intervals use the delta method with the joint covariance of
the fitted parameters, including uncertainty in the breakpoint or logistic
width. By default they include intercept uncertainty and its covariance
with the curve, without adding the intercept to the estimated contribution.
Use overall_uncertainty = FALSE for term-only uncertainty. At the
breakpoint, the derivative is taken from the constant side, matching native
sdmTMB prediction. Threshold intervals remain pointwise when simultaneous
smooth bands are requested. Rugs show fitting observations.
Time-varying coefficients are plotted at their stored time steps, including
extra_time; n does not add time steps. Select each fitted design column
with a label such as time_varying(temperature) or
time_varying(Intercept). A covariate named Intercept is distinguished
from the intercept by backticks: time_varying(`Intercept`).
Factor contrasts, transformations and interactions
retain the fitted coefficient coding. For rw, estimates are the temporal
coefficients. For rw0 and ar1, the matching ordinary coefficient is added
to its temporal deviation. Their joint covariance includes the variance of
both parts and their covariance. An absent ordinary coefficient contributes
zero. Matching columns must have compatible coding in the main and temporal
designs. Default effects omit ordinary terms whose coefficients are already
included in trajectories; their ordinary selectors remain available for
explicit requests. overall_uncertainty governs ordinary partial effects;
temporal panels always retain their complete coefficient covariance.
Temporal intervals remain pointwise when simultaneous smooth bands are
requested. Supplied data selects stored time steps if it contains the
model's time column; otherwise all stored times are retained. Missing or
unknown requested times give an error. sdmTMB 1.2.0 requires numeric time
values for time-varying processes.
Time-varying estimates from parametric_effects() use .type = "time_varying", .value for time, .partial for the full coefficient,
and .se for its standard error. Both display styles are also available
through draw.parametric_effects(), including nested saved estimates.
Smooth extraction and effect plots do not support dispersion formulas, other multi-predictor families, or nonlocal effects. Spatial fields and group random effects are not plotted.
Smooth labels, smooth objects, coefficients, effect estimates, or
plots, as for the corresponding GAM methods. draw() returns a patchwork,
or named panels with wrap = FALSE; assemble() returns an
assembled_plots list. Models without smooths can draw parametric effects.
Pass label_control = draw_label_control(...) to draw() to wrap discrete
axis labels and legend text, stagger discrete tick labels, or adjust legend
and colour-bar layout. Settings apply to each panel, including unwrapped
plot lists. See draw_label_control() for the available settings.
if (requireNamespace("sdmTMB", quietly = TRUE)) { load_mgcv() # Simulate nonlinear and linear effects with Gaussian noise set.seed(42) d <- data.frame(x = runif(150), z = runif(150)) d$y <- 1 + sin(6 * d$x) + 0.5 * d$z + rnorm(150, sd = 0.3) # Fit without a spatial field and draw the linear and smooth effects m <- sdmTMB::sdmTMB(y ~ z + s(x, k = 6), data = d, spatial = "off") smooths(m) draw(m) }if (requireNamespace("sdmTMB", quietly = TRUE)) { load_mgcv() # Simulate nonlinear and linear effects with Gaussian noise set.seed(42) d <- data.frame(x = runif(150), z = runif(150)) d$y <- 1 + sin(6 * d$x) + 0.5 * d$z + rnorm(150, sd = 0.3) # Fit without a spatial field and draw the linear and smooth effects m <- sdmTMB::sdmTMB(y ~ z + s(x, k = 6), data = d, spatial = "off") smooths(m) draw(m) }
Creates a sequence of n evenly-spaced values over the range
min(x) – max(x), where the minimum and maximum are adjusted such that
they are always contained within the range of x when x may be shifted
forwards or backwards by an amount related to eps. This is particularly
useful in computing derivatives via finite differences where without this
adjustment we may be predicting for values outside the range of the data
and hence the constraints of the penalty.
seq_min_max_eps(x, n, order, type = c("forward", "backward", "central"), eps)seq_min_max_eps(x, n, order, type = c("forward", "backward", "central"), eps)
x |
numeric; vector over which evenly-spaced values are returned |
n |
numeric; the number of evenly-spaced values to return |
order |
integer; the order of derivative. Either |
type |
character; the type of finite difference used. One of
|
eps |
numeric; the finite difference |
A numeric vector of length n.
Represent the set of coefficient vectors whose evaluated functions are inside an initial band and satisfy supplied linear inequalities and equalities.
shape_confidence_set( X, lower, upper, Ain = NULL, bin = NULL, C = NULL, d = NULL, level = 0.95, interpretation = c("confidence", "credible"), band_type = c("unspecified", "simultaneous", "pointwise") ) in_shape_set(object, coefficients, tolerance = 1e-08)shape_confidence_set( X, lower, upper, Ain = NULL, bin = NULL, C = NULL, d = NULL, level = 0.95, interpretation = c("confidence", "credible"), band_type = c("unspecified", "simultaneous", "pointwise") ) in_shape_set(object, coefficients, tolerance = 1e-08)
X |
A finite numeric matrix that maps coefficients to function values at the evaluation points. Each column corresponds to a coefficient. |
lower, upper
|
Numeric vectors of lower and upper limits, one per row of
|
Ain |
A finite numeric matrix defining inequalities |
bin |
A finite numeric vector, one entry per row of |
C |
A finite numeric matrix defining equalities |
d |
A finite numeric vector, one entry per row of |
level |
A number strictly between zero and one recording the nominal level of the initial band. This does not calibrate the band. |
interpretation |
Is the initial band a confidence or credible band? |
band_type |
Record whether the initial limits were calibrated jointly
( |
object |
A set created by |
coefficients |
A finite numeric vector, or a finite numeric matrix with
one candidate coefficient vector in each column. Rows must correspond to
columns of |
tolerance |
A finite non-negative number used as an absolute tolerance
in function values and constraint residuals. The default is |
The returned object represents the set
The matrices are retained explicitly; the function does not optimise over the set, test whether it is empty, or draw samples from it. Redundant and inconsistent restrictions are allowed. Inconsistent restrictions represent an empty set.
The initial band restricts function values only at the supplied evaluation points. The extent of the shape restriction depends on the supplied coefficient inequalities. For example, appropriate spline coefficient inequalities can guarantee monotonicity throughout a spline's domain, whereas differences between evaluated function values guarantee it only on that grid. This function does not infer restrictions from a fitted model or extend restrictions between evaluation points.
If the true coefficient vector satisfies the supplied restrictions, it is in the intersection exactly when its evaluated function is in the initial band. Thus intersection preserves the coverage of an initially valid simultaneous confidence band, for truths satisfying those restrictions. Pointwise limits alone do not supply a simultaneous confidence set. For credible bands, the same posterior probability statement requires the posterior to be supported entirely on the restricted coefficient space. Intersection does not fix smoothing bias, invalid initial calibration, or an incorrect restriction.
Coordinatewise minima and maxima of functions in this set need not themselves belong to the set. This matters for coupled restrictions such as an integral equal to one: two ordered functions with that integral must coincide almost everywhere. Retaining the whole set avoids assigning such equalities to separate endpoint curves.
shape_confidence_set() returns a list of class
"shape_confidence_set" containing X, lower, upper, Ain, bin, C,
d, level, interpretation, and band_type. Missing constraint matrices
are stored as matrices with zero rows. in_shape_set() returns a logical
vector, one value per candidate coefficient vector.
# Two non-negative masses whose sum is one. region <- shape_confidence_set( X = diag(2), lower = c(0.1, 0.2), upper = c(0.8, 0.9), Ain = diag(2), C = matrix(c(1, 1), nrow = 1), d = 1, band_type = "simultaneous" ) in_shape_set(region, c(0.4, 0.6)) in_shape_set(region, c(0.4, 0.7))# Two non-negative masses whose sum is one. region <- shape_confidence_set( X = diag(2), lower = c(0.1, 0.2), upper = c(0.8, 0.9), Ain = diag(2), C = matrix(c(1, 1), nrow = 1), d = 1, band_type = "simultaneous" ) in_shape_set(region, c(0.4, 0.6)) in_shape_set(region, c(0.4, 0.7))
Apply shape-enforcing operators to an existing estimate and its lower and upper endpoints. Construction and calibration of the initial uncertainty remain the caller's responsibility.
shape_intervals( estimate, lower, upper, data, constraints, interval = c("simultaneous", "pointwise"), level = 0.95 )shape_intervals( estimate, lower, upper, data, constraints, interval = c("simultaneous", "pointwise"), level = 0.95 )
estimate, lower, upper
|
finite numeric vectors, one value per row of
|
data |
a data frame of finite numeric coordinates. Rows may be in any order but must form a complete Cartesian product without duplicates. Coordinates may be irregularly spaced. A single coordinate gives a curve. |
constraints |
a named list, with coordinate names as names and character
vectors of restrictions as elements. Codes are |
interval |
character; whether the input is a |
level |
numeric; the nominal level of the input, strictly between zero and one. |
The operator first thresholds at zero if requested, then sorts each
monotone coordinate in the order given by constraints, then takes the
greatest convex minorant in the curvature coordinate. Concavity uses the
negative of the greatest convex minorant of the negative values. The
minorant uses actual coordinate distances. Sorting gives equal mass to each
grid coordinate, including on irregular grids; it does not approximate
Lebesgue-weighted rearrangement on such grids.
These finite-grid operators preserve order, leave a function with the requested shapes unchanged, and do not increase maximum absolute distance. Consequently, whenever the entire initial band contains a target with the requested shapes on the grid, the transformed band also contains it. Its maximum width cannot increase. This is a deterministic statement about a whole-grid event; it does not guarantee nominal pointwise coverage after transforming pointwise limits. Nor does it correct smoothing bias or an invalid initial uncertainty calculation. For a posterior supported on the restricted functions the analogous event inclusion applies to posterior probability; this operation does not construct that posterior.
The guarantees concern values on the supplied grid. Linear interpolation
of curves, or multilinear interpolation on rectangles, also has the named
directional shapes between grid points. The output is not a fitted spline
and need not obey coefficient inequalities, centring, integral constraints,
or other equalities. Use shape_confidence_set() to represent intersections
with such restrictions. Several curvature coordinates are unsupported:
sequential directional convexification need not preserve earlier convexity.
Extreme numeric ranges that prevent reliable slope comparisons or
interpolation in double precision produce an error.
A tibble containing data, .estimate, .lower_ci, and
.upper_ci, in the original row order. The interval_info attribute
records the operator, restrictions, input interval type and coverage scope.
Standard errors and Gaussian critical values are not recalculated.
Chernozhukov, V., Fernandez-Val, I. and Galichon, A. (2009). Improving point and interval estimators of monotone functions by rearrangement. Biometrika, 96, 559–575. doi:10.1093/biomet/asp030.
Chen, X., Chernozhukov, V., Fernandez-Val, I., Kostyshak, S. and Luo, Y. (2021). Shape-Enforcing Operators for Generic Point and Interval Estimators of Functions. Journal of Machine Learning Research, 22(220), 1–42. https://www.jmlr.org/papers/v22/20-513.html.
x <- c(0, 0.1, 0.4, 0.8, 1) f <- c(0.1, 0.4, 0.2, 0.9, 0.7) shape_intervals(f, f - 0.3, f + 0.3, data.frame(x = x), constraints = list(x = c("+", "m+")))x <- c(0, 0.1, 0.4, 0.8, 1) f <- c(0.1, 0.4, 0.2, 0.9, 0.7) shape_intervals(f, f - 0.3, f + 0.3, data.frame(x = x), constraints = list(x = c("+", "m+")))
eps
Shift numeric values in a data frame by an amount eps
shift_values(df, h, i, FUN = `+`, focal = NULL)shift_values(df, h, i, FUN = `+`, focal = NULL)
df |
a data frame or tibble. |
h |
numeric; the amount to shift values in |
i |
logical; a vector indexing columns of |
FUN |
function; a function to apply the shift. Typically |
focal |
character; the focal variable when computing partial
derivatives. This allows shifting only the focal variable by |
Generate replicated responses using fitted parameter values.
posterior_samples() also includes uncertainty in the coefficients.
See diagnostic_support.
## S3 method for class 'gamm4' simulate(object, nsim = 1, seed = NULL, conditioning = NULL, ...) ## S3 method for class 'gamlss' simulate(object, nsim = 1L, seed = NULL, ...) ## S3 method for class 'gam' simulate( object, nsim = 1, seed = NULL, data = newdata, weights = NULL, ..., newdata = NULL, family_index = NULL, envir = NULL, marginalise = NULL ) ## S3 method for class 'gamm' simulate( object, nsim = 1, seed = NULL, data = newdata, weights = NULL, ..., newdata = NULL, conditioning = NULL, envir = NULL ) ## S3 method for class 'scam' simulate( object, nsim = 1, seed = NULL, data = newdata, weights = NULL, ..., newdata = NULL, envir = NULL )## S3 method for class 'gamm4' simulate(object, nsim = 1, seed = NULL, conditioning = NULL, ...) ## S3 method for class 'gamlss' simulate(object, nsim = 1L, seed = NULL, ...) ## S3 method for class 'gam' simulate( object, nsim = 1, seed = NULL, data = newdata, weights = NULL, ..., newdata = NULL, family_index = NULL, envir = NULL, marginalise = NULL ) ## S3 method for class 'gamm' simulate( object, nsim = 1, seed = NULL, data = newdata, weights = NULL, ..., newdata = NULL, conditioning = NULL, envir = NULL ) ## S3 method for class 'scam' simulate( object, nsim = 1, seed = NULL, data = newdata, weights = NULL, ..., newdata = NULL, envir = NULL )
object |
a fitted GAM, typically the result of a call to |
nsim |
numeric; number of response simulations to return. Supply one
finite positive whole number, no larger than |
seed |
numeric or |
conditioning |
character or |
... |
arguments passed to methods. |
data |
data frame; new observations at which the posterior draws
from the model should be evaluated. If not supplied, the data used to fit
the model will be used for |
weights |
numeric; response sampling weights. An explicit vector
overrides the fitting weights; a single value applies to every observation.
With |
newdata |
Deprecated. Use |
family_index |
numeric; for grouped-family models, one integer family index per requested prediction row. See Details. |
envir |
environment or |
marginalise |
|
For simulate.gam() to function, the family component of the fitted
model must contain, or be updatable to contain, the required random
number generator. See mgcv::fix.family.rd().
With marginalise, each replicate draws new coefficients for selected
re and fs terms before drawing responses. Other coefficients and all
variance parameters stay fixed. Supply grouping columns for new data;
repeated group labels share effects within a replicate. Unfamiliar labels
are allowed only when those factors occur exclusively in selected terms.
The random_effect_info attribute records the fixed covariance estimates.
With data = NULL, na.exclude restores excluded observations as NA in
every simulation; na.omit returns retained observations only. Positions
refer to the fitting data after any subset. Explicit data are evaluated
independently of training exclusions: missing responses do not prevent
simulation, while missing required predictors or weights yield NA.
Prediction na.action in ... is honoured. Missing rows are never passed
to the response random-number generator.
Inverse Gaussian models use a native generator with observation dispersion
equal to the model dispersion divided by the prior weight, consistently with
their CDF and quantile helpers. Weights must be non-negative; a zero weight
with positive dispersion uses the limiting point mass at zero. An existing
random generator supplied in the family's rd component is preserved.
For models fitted with mgcv::gfam(), each observation is simulated from
its component family using that component's fitted scale and distribution
parameters. With data = NULL, fitted family membership is used. For explicit
data, supply family_index or the index in the model's response expression:
the second column of a matrix response, the second argument of cbind(y, index),
or a numeric index vector in place of a named matrix response. Actual response
observations are not needed. Missing indices follow prediction na.action;
invalid indices are errors. Explicit indices must agree with recoverable ones.
Grouped simulations return one numeric response per observation: binomial
proportions (with integer trial counts supplied in weights), count responses,
or ordered-category codes, as appropriate. Component random generators retain
their usual treatment of prior weights. Ordered-categorical and ziP components
are simulated from their latent predictors. General families with multiple
linear predictors and matrix responses encoding censoring or binomial counts
are outside the scope supported by gfam(). Scalar censored-family components
produce draws from their uncensored latent distributions.
(Currently) A data frame with nsim columns.
Gavin L. Simpson
load_mgcv() dat <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") sims <- simulate(m1, nsim = 5, seed = 42) head(sims)load_mgcv() dat <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") sims <- simulate(m1, nsim = 5, seed = 42) head(sims)
Simulation calibrates Gaussian bands jointly over the returned evaluation points. Tube calibration covers a continuous interval for supported one-dimensional cubic splines, including the space between returned points.
Request interval = "simultaneous" and
simultaneous_method = "tube". The simulation method remains the default.
Tube bands use the same Gaussian coefficient covariance selected by
frequentist and unconditional as simulation. For smooth estimates they
also retain overall_uncertainty. They calibrate separately for each smooth
or factor-level comparison; they do not cover all comparisons jointly.
Let be the uncertainty design and the coefficient
covariance. With , set
. The method integrates
and chooses so that
This expression bounds the two-sided exceedance probability by counting threshold crossings of the standardized Gaussian process. Repeated paths can make it conservative. Regular components separated by zero variance receive separate endpoint contributions. Polynomial knots divide numerical integration, but do not add endpoint contributions when the process is continuous. Zero-variance and rank-one processes are handled separately.
Under the selected Gaussian approximation, the band has at least the
requested simultaneous probability over the stated interval, subject to
numerical accuracy. Bayesian covariance gives an approximate posterior
interpretation. Frequentist covariance calibrates centered Gaussian sampling
errors; coverage of an unknown fixed curve also depends on smoothing bias.
The unconditional covariance correction retains its existing meaning and
does not integrate the full smoothing-parameter posterior. Numerical
integration error estimates are diagnostics, not certified error bounds.
Ordinary one-dimensional cubic regression splines ("cr", "cs"),
cubic P-splines ("ps" with their ordinary cubic degree), and ordinary
cubic thin plate bases ("tp", "ts") are supported. Factor-by smooths
define separate curves. Numeric by multipliers must be fixed throughout
each curve. Unconstrained GAMs and their BAM, GAMM, and GAMM4 adapters use
their fitted prediction basis and covariance. Surfaces, constrained models,
shape enforcement, and unsupported bases produce an error; there is no
automatic switch to simulation.
First and second derivative bands retain the requested finite-difference
functional, stencil, and step. The operator is evaluated using integrals
of spline derivatives to avoid subtracting nearly equal basis values.
This can improve floating-point accuracy relative to the simulation path
without changing the mathematical functional. The continuous band refers
to that derivative approximation. Differentiation must be on the smooth
coordinate (wrt = "smooth", or the same coordinate on the covariate scale).
Raw-scale derivatives of transformed terms are not supported by tube
calibration. Difference bands retain the joint covariance of the two
smooths and include group means when requested. The selected parametric
group contributions must be constant along the curve.
simultaneous_domain accepts two increasing finite endpoints, or a named
list keyed by coordinate. By default it is the range of returned evaluation
coordinates, including gaps. A single evaluation location requires an
explicit interval. All returned points must lie inside the domain, which
must lie inside the fitted spline support; derivative stencils must also
remain inside that support. The domain does not imply that each compared
group has observations throughout it. With a fixed domain, n changes
output density but does not change calibration. Connecting plotted bounds
by straight segments is a rendering approximation to the continuous band.
tube_control accepts rel_tol = 1e-6, abs_tol = 1e-8,
subdivisions = 1000L, and root_tol = 1e-8. Integration is split at
polynomial boundaries and checked for convergence. Failures produce errors.
Simulation controls (n_sim, n_cores/ncores, and seed) are ignored;
tube calibration does not use random numbers. Computation controls require
the fitted model. Drawing saved estimates uses their stored interval limits.
The interval_info attribute records calibration = "tube",
calculation = "tube_crossing_bound", the Gaussian covariance flags, and
the per-smooth or per-comparison coverage scope. Its curves list contains
identities, coordinates, resolved domains and their sources, critical
values, lengths, regular-component counts, numerical diagnostics, and
derivative stencils and steps where applicable. Methodological details are
not added to plot captions.
Sun, J. and Loader, C. R. (1994). Simultaneous confidence bands for linear regression and smoothing. The Annals of Statistics, 22, 1328–1345. doi:10.1214/aos/1176325631.
Krivobokova, T., Kneib, T. and Claeskens, G. (2010). Simultaneous confidence bands for penalized spline estimators. Journal of the American Statistical Association, 105, 852–863. doi:10.1198/jasa.2010.tm09165.
Wiesenfarth, M., Krivobokova, T., Klasen, S. and Sperlich, S. (2012). Direct simultaneous inference in additive models and its application to model undernutrition. Journal of the American Statistical Association, 107, 1286–1296.
Liebl, D. and Reimherr, M. (2023). Fast and fair simultaneous confidence bands for functional parameters. Journal of the Royal Statistical Society: Series B, 85, 842–868. doi:10.1093/jrsssb/qkad026.
smooth_estimates(), derivatives(), difference_smooths(),
confint.gam(), draw.gam()
load_mgcv() set.seed(4) dat <- data.frame(x = seq(0, 1, length.out = 100)) dat$y <- sin(6 * dat$x) + rnorm(100, sd = 0.2) model <- gam(y ~ s(x, bs = "cr", k = 8), data = dat, method = "REML") band <- smooth_estimates(model, interval = "simultaneous", simultaneous_method = "tube", simultaneous_domain = c(0, 1) ) draw(band) rate <- derivatives(model, type = "central", interval = "simultaneous", simultaneous_method = "tube" ) attr(rate, "interval_info")$curves[[1]]$criticalload_mgcv() set.seed(4) dat <- data.frame(x = seq(0, 1, length.out = 100)) dat$y <- sin(6 * dat$x) + rnorm(100, sd = 0.2) model <- gam(y ~ s(x, bs = "cr", k = 8), data = dat, method = "REML") band <- smooth_estimates(model, interval = "simultaneous", simultaneous_method = "tube", simultaneous_domain = c(0, 1) ) draw(band) rate <- derivatives(model, type = "central", interval = "simultaneous", simultaneous_method = "tube" ) attr(rate, "interval_info")$curves[[1]]$critical
A dataset containing lead-210 based age depth measurements for the SMALL1 core from Small Water.
A data frame with 12 rows and 7 variables.
The variables are as follows:
Depth
Drymass
Date
Age
Error
SedAccRate
SedPerCentChange
Simpson, G.L. (Unpublished data).
Returns a vector of indices of the parametric terms that represent the supplied smooth. Useful for extracting model coefficients and columns of their covariance matrix.
smooth_coef_indices(smooth)smooth_coef_indices(smooth)
smooth |
an object that inherits from class |
A numeric vector of indices.
Gavin L. Simpson
smooth_coefs() for extracting the coefficients for a particular
smooth.
Returns a vector of model coefficients of the parametric terms that represent the supplied smooth.
smooth_coefs(object, ...) ## S3 method for class 'gam' smooth_coefs(object, select, term = deprecated(), ...) ## S3 method for class 'bam' smooth_coefs(object, select, term = deprecated(), ...) ## S3 method for class 'gamm' smooth_coefs(object, select, term = deprecated(), ...) ## S3 method for class 'gamm4' smooth_coefs(object, select, term = deprecated(), ...) ## S3 method for class 'mgcv.smooth' smooth_coefs(object, model, ...) ## S3 method for class 'scam' smooth_coefs(object, select, term = deprecated(), ...)smooth_coefs(object, ...) ## S3 method for class 'gam' smooth_coefs(object, select, term = deprecated(), ...) ## S3 method for class 'bam' smooth_coefs(object, select, term = deprecated(), ...) ## S3 method for class 'gamm' smooth_coefs(object, select, term = deprecated(), ...) ## S3 method for class 'gamm4' smooth_coefs(object, select, term = deprecated(), ...) ## S3 method for class 'mgcv.smooth' smooth_coefs(object, model, ...) ## S3 method for class 'scam' smooth_coefs(object, select, term = deprecated(), ...)
object |
a fitted GAM(M) object, or, for the |
... |
arguments passed to other methods. |
select |
character; the label of the smooth whose coefficients will be returned. |
term |
|
model |
a fitted GAM(M) object. |
A numeric vector of model coefficients.
Gavin L. Simpson
smooth_coef_indices() for extracting the indices of the
coefficients for a particular smooth.
load_mgcv() df <- data_sim("eg1", seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## IGNORE_RDIFF_BEGIN smooth_coefs(m, select = "s(x2)") ## IGNORE_RDIFF_ENDload_mgcv() df <- data_sim("eg1", seed = 2) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") ## IGNORE_RDIFF_BEGIN smooth_coefs(m, select = "s(x2)") ## IGNORE_RDIFF_END
Generate regular data over the covariates of a smooth
smooth_data( model, id, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, offset = NULL, include_all = FALSE, var_order = NULL, envir = NULL, back_transform = FALSE )smooth_data( model, id, n = 100, n_2d = NULL, n_3d = NULL, n_4d = NULL, offset = NULL, include_all = FALSE, var_order = NULL, envir = NULL, back_transform = FALSE )
model |
a fitted model |
id |
the number ID of the smooth within |
n |
numeric; the number of new observations to generate. |
n_2d |
numeric; the number of points along each of the first two axes
of a smooth surface, including surface panels of higher-dimensional smooths.
The default, |
n_3d |
numeric; the number of new observations to generate for the third dimension of a 3D smooth. For factor conditioning dimensions, retain at most this many levels, taking the first in fitted order. |
n_4d |
numeric; the number of new observations to generate for the
dimensions higher than 2 (!) of a kD smooth (k >= 4). For example, if
the smooth is a 4D smooth, each of dimensions 3 and 4 will get |
offset |
numeric; value of the model offset to use. |
include_all |
logical; include all covariates involved in the smooth?
if |
var_order |
character; the order in which the terms in the smooth should be processed. Only useful for tensor products with at least one 2d marginal smooth. |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
back_transform |
logical; generate the grid on original covariate
scales? The default, |
Spline-on-the-sphere grids use evenly spaced observed-range latitude and longitude values. Plotting constructs geographic cell edges separately, without moving these evaluation coordinates.
load_mgcv() df <- data_sim("eg1", seed = 42) m <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df) # generate data over range of x1 for smooth s(x1) smooth_data(m, id = 2) # generate data over range of x1 for smooth s(x1), with typical value for # other covariates in the model smooth_data(m, id = 2, include_all = TRUE)load_mgcv() df <- data_sim("eg1", seed = 42) m <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df) # generate data over range of x1 for smooth s(x1) smooth_data(m, id = 2) # generate data over range of x1 for smooth s(x1), with typical value for # other covariates in the model smooth_data(m, id = 2, include_all = TRUE)
Extracts the dimension of an estimated smooth.
## S3 method for class 'gamm4' smooth_dim(object) smooth_dim(object) ## S3 method for class 'gam' smooth_dim(object) ## S3 method for class 'gamm' smooth_dim(object) ## S3 method for class 'mgcv.smooth' smooth_dim(object)## S3 method for class 'gamm4' smooth_dim(object) smooth_dim(object) ## S3 method for class 'gam' smooth_dim(object) ## S3 method for class 'gamm' smooth_dim(object) ## S3 method for class 'mgcv.smooth' smooth_dim(object)
object |
an R object. See Details for list of supported objects. |
This is a generic function with methods for objects of class
"gam", "gamm", and "mgcv.smooth".
A numeric vector of dimensions for each smooth.
Gavin L. Simpson
Evaluate a smooth at a grid of evenly spaced value over the range of the
covariate associated with the smooth. Alternatively, a set of points at which
the smooth should be evaluated can be supplied. smooth_estimates() is a new
implementation of evaluate_smooth(), and replaces that function, which has
been removed from the package.
smooth_estimates(object, ...) ## S3 method for class 'gam' smooth_estimates( object, select = NULL, smooth = deprecated(), n = 100, n_2d = 50, n_3d = 16, n_4d = 4, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, unnest = TRUE, partial_match = FALSE, clip = FALSE, envir = NULL, back_transform = FALSE, interval = NULL, ci_level = 0.95, n_sim = 10000, n_cores = 1, seed = NULL, interval_method = c("auto", "gaussian", "bootstrap", "shape"), shape_source = c("gaussian", "bootstrap"), ..., variables = NULL, simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list() ) ## S3 method for class 'gamlss' smooth_estimates( object, select = NULL, smooth = deprecated(), ..., partial_match = FALSE ) ## S3 method for class 'gjrm' smooth_estimates( object, select = NULL, smooth = deprecated(), ..., partial_match = FALSE )smooth_estimates(object, ...) ## S3 method for class 'gam' smooth_estimates( object, select = NULL, smooth = deprecated(), n = 100, n_2d = 50, n_3d = 16, n_4d = 4, data = NULL, unconditional = FALSE, frequentist = FALSE, overall_uncertainty = TRUE, dist = NULL, unnest = TRUE, partial_match = FALSE, clip = FALSE, envir = NULL, back_transform = FALSE, interval = NULL, ci_level = 0.95, n_sim = 10000, n_cores = 1, seed = NULL, interval_method = c("auto", "gaussian", "bootstrap", "shape"), shape_source = c("gaussian", "bootstrap"), ..., variables = NULL, simultaneous_method = c("simulation", "tube"), simultaneous_domain = NULL, tube_control = list() ) ## S3 method for class 'gamlss' smooth_estimates( object, select = NULL, smooth = deprecated(), ..., partial_match = FALSE ) ## S3 method for class 'gjrm' smooth_estimates( object, select = NULL, smooth = deprecated(), ..., partial_match = FALSE )
object |
a fitted model, including objects of class |
... |
arguments passed to other methods. |
select |
character, numeric or logical; smooths to evaluate, using labels
from |
smooth |
|
n |
numeric; the number of points over the range of the covariate at which to evaluate a univariate smooth. |
n_2d |
numeric; the number of points along each of the first two axes
of a smooth surface, including surface panels of higher-dimensional smooths.
The default is 50 in plotting and plot-preparation functions. If |
n_3d, n_4d
|
numeric; the number of points along the third axis of a
3D smooth ( |
data |
a data frame of covariate values at which to evaluate the smooth. |
unconditional |
logical; if |
frequentist |
logical; if |
overall_uncertainty |
logical; should the uncertainty in the model constant term be included in the standard error of the evaluate values of the smooth? |
dist |
numeric; if greater than 0, this is used to determine when
a location is too far from data to be plotted when plotting 2-D smooths.
The data are scaled into the unit square before deciding what to exclude,
and |
unnest |
logical; unnest the smooth objects? |
partial_match |
logical; in the case of character |
clip |
logical; should evaluation points be clipped to the boundary of
a soap film smooth? The default is |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
back_transform |
logical; generate automatic grids on the original
covariate scale? The default, |
interval |
character or |
ci_level |
numeric; interval coverage, strictly between zero and one. |
n_sim, n_cores
|
positive integers; coefficient draws and simulation cores for simultaneous bands. Parallel simulation requires OpenMP support. |
seed |
integer or |
interval_method |
character; "auto" uses stored scasm bootstrap draws
for pointwise intervals when available, and Gaussian intervals otherwise.
Use "gaussian" to request covariance-based limits or "bootstrap" to
require stored draws. Simultaneous bootstrap bands are not supported.
|
shape_source |
character; initial uncertainty for |
variables |
Character vector giving every covariate of the selected
smooths exactly once, in plotting order: x, y, then the conditioning
covariate for 3D smooths, or facet rows and columns for 4D smooths.
When supplied, selected smooths must use the same covariates. Use fitted coordinate names,
such as |
simultaneous_method |
character; calibration for simultaneous bands.
The default, |
simultaneous_domain |
numeric pair of increasing finite endpoints, or
a named list of such pairs keyed by spline coordinate. For tube bands,
|
tube_control |
named list controlling numerical tube calibration:
|
For GJRM::gamlss() and GJRM::gjrm() models, smooths are evaluated in equation and smooth
order using the final fitted GJRM coefficients and covariance matrices.
Selection uses the model-wide labels returned by smooths(), including
suffixes such as s.1(x) for repeated labels. Equations without smooths
are skipped; a model without any smooths gives an error. All grid, data,
environment, coordinate transformation and interval controls are passed to
the GAM method for each selected equation. frequentist = TRUE uses the
final GJRM frequentist covariance. A smoothing-parameter uncertainty
correction is unavailable: unconditional = TRUE warns and uses the
uncorrected final covariance, as for GAMs without that correction.
For distributional and glmmTMB models with multiple linear predictors,
an optional .model column identifies the model part or parameter
associated with each smooth. This display metadata is retained in nested
output and subsets, allowing draw() to reproduce model subtitles from saved
estimates. Smooth labels and selection remain unchanged.
When distinct fitted terms share both their smooth label and type (for
example, tensor products of soap-film components), .smooth_id contains
their fitted smooth indices. This preserves their identity in saved
estimates and plots without changing the labels supplied by mgcv.
By default, simultaneous coverage is per fitted smooth over its valid evaluation points,
including all its slices and factor levels. Separate factor-by smooths remain
separate coverage sets when grouped in one plot. This finite-grid band does
not claim joint coverage across selected smooths or the full fitted model.
Increasing grid resolution improves the approximation to whole-curve coverage.
For supported univariate cubic splines, simultaneous_method = "tube"
instead calibrates over a continuous interval; see simultaneous_bands.
overall_uncertainty and covariance options apply to both interval types.
SCAM smooth estimates retain the fitted centring and coefficient
transformation when evaluation points are changed. Pointwise intervals use
the covariance of the constrained coefficients. With
overall_uncertainty = TRUE, their standard errors also include intercept
uncertainty and its covariance with the smooth; estimates remain centred.
Models without an intercept use smooth-only uncertainty for either setting.
Native scasm fits use component-only uncertainty by default. Explicitly
requesting overall_uncertainty = TRUE warns once if selected smooths lack
the centring information needed to add mean uncertainty. Ordinary GAM
defaults are unchanged.
Bootstrap pointwise limits follow mgcv's percentiles and its svar.only
correction for smoothing bias. The correction can move limits beyond the
fitted shape constraints. Estimates and covariance-based standard errors
are unchanged; .crit is NA for asymmetric bootstrap limits. No new
replicates are generated. Simultaneous intervals use Gaussian draws and
warn if automatic selection leaves stored bootstrap draws unused.
The interval_info attribute records the interval source and correction.
The shape_constraints attribute identifies requests and retained
inequalities for each fitted smooth and tensor margin. Captions use
plotmath arrows for increasing and decreasing constraints while .type
and smooth_type() keep their existing basis names. Unsupported tensor
requests produce a warning and are labelled as not retained.
SCAM captions describe the basis and its constraints separately from the
compact .type values. Increasing and decreasing constraints use plotmath
arrows. Tensor captions name each covariate and its constraint; local
constraints include the fitted change point. The scam_smooth_info
attribute preserves these descriptions when plotting saved estimates.
Shape enforcement is explicit and leaves the existing interval defaults
unchanged. It preserves containment of a shape-restricted target whenever
the entire initial band contains that target on the evaluation grid. This
does not establish nominal coverage of the initial band, or preserve
marginal coverage of transformed pointwise limits. The default Gaussian
source uses approximate Bayesian covariance and does not construct a
constrained posterior. Standard errors describe the initial calculation;
.crit is NA after shape enforcement. Metadata records the initial source,
correction, named shapes, model coordinates and whole-grid guarantee.
Every selected term must have retained named scasm restrictions. Supported
combinations are positivity, monotonicity in any directions and curvature
in at most one direction. Tensor smooths require te(..., np = FALSE) with
univariate B-spline margins ("sc" or "bs"). Normal reparameterisation
and other complementary bases can invalidate the named surface shape even
when coefficient inequalities were retained. Curvature additionally
requires equally spaced fitted knots to rounding precision and degree at
least two. Irregular evaluation
coordinates are supported. Complete product grids, finite endpoints and
evaluation inside the fitted B-spline domains are required; use dist = 0
for tensors. Numeric by variables are unsupported; factor-by components
and separate linear predictors are treated separately.
Function-valued bases are required; derivative bases are unsupported.
General pc inequalities can replace the named coefficient restrictions
while leaving their original xt request in the fitted object. These
replacements are labelled as general constraints and rejected for automatic
shape intervals. Point equalities that retain the named inequalities are
supported.
Shape intervals use component-only uncertainty: explicit
overall_uncertainty = TRUE, effect shifts and effect transformations are
rejected. Coordinate transformations used in the model remain supported;
their named shapes concern model coordinates. The transformed endpoints
need not belong to the fitted spline space or obey centring equalities.
See shape_confidence_set() for explicit coefficient restrictions and the
shape-constrained intervals article
for examples.
Smoothing-parameter uncertainty is not currently supported for SCAM models;
use unconditional = FALSE.
For explicit data, missing covariates needed by a smooth produce NA
estimates and standard errors at those positions. Missing values in variables
unrelated to that smooth do not discard its otherwise evaluable rows.
Raw data may contain x for a smooth such as s(log(x)); gratia evaluates
the expression before constructing the prediction matrix. An evaluated
column named "log(x)" can be supplied instead. When both are supplied,
the raw inputs take precedence, except for stored model frames and grids
prepared by gratia. Automatic grids are evenly spaced in the smooth
coordinate (log(x)), and returned coordinate columns retain that name.
Stored evaluated columns allow automatic plotting even when a local function
used to fit the model is no longer available. Evaluating that function at new
raw data requires envir; training values are never substituted for new
observations. Arbitrary transformations are not inverted to recover raw data.
The coordinate_info attribute identifies retained raw coordinate columns.
draw() uses them for back_transform = TRUE; the usual coordinate
columns remain on the model scale. Automatic raw grids require recoverable
fitting rows and matching functions and constants. Supplied raw data
instead define the prediction rows directly.
Typical covariate values added to evaluated grids by include_all = TRUE
are not raw axis coordinates. Numeric by multipliers are set to one on
automatic grids, even when their name also identifies a raw axis; supplied
prediction rows retain their actual multipliers. Soap-film boundary rows
retain model coordinates only. If a boundary axis is transformed, draw the
estimates with back_transform = FALSE; raw-scale drawing gives an error
rather than dropping the boundary.
A data frame (tibble), which is of class "smooth_estimates".
Its plot_variables attribute is a list of resolved covariate orders,
named by smooth label, used when drawing the saved estimates.
Its cyclic_info attribute retains the fitted cycle boundaries for
supported one-dimensional cyclic components, allowing
draw(object, cyclic = "polar") to configure the angular axis.
This attribute is retained in nested and unnested output.
When no evaluation rows remain, flat output has zero rows and retains the
estimate, standard error and predictor columns with their original types.
With unnest = FALSE, each selected smooth retains its metadata record
and a data table with zero rows in the data list column.
load_mgcv() dat <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") ## evaluate all smooths smooth_estimates(m1) ## or selected smooths smooth_estimates(m1, select = c("s(x0)", "s(x1)")) # Direct evaluation of a GJRM distributional model if (requireNamespace("GJRM", quietly = TRUE)) { set.seed(82) d <- data.frame(x = runif(100), z = runif(100)) d$y <- sin(6 * d$x) + rnorm(100, sd = exp(0.3 * d$z)) m <- GJRM::gamlss(list(y ~ s(x, k = 4), ~ s(z, k = 4)), data = d) estimates <- smooth_estimates(m, n = 50) draw(estimates) } # parallel processing of smooths if (requireNamespace("mirai") && requireNamespace("carrier")) { library("mirai") daemons(2) # only low for CRAN requirements smooth_estimates(m1) }load_mgcv() dat <- data_sim("eg1", n = 400, dist = "normal", scale = 2, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") ## evaluate all smooths smooth_estimates(m1) ## or selected smooths smooth_estimates(m1, select = c("s(x0)", "s(x1)")) # Direct evaluation of a GJRM distributional model if (requireNamespace("GJRM", quietly = TRUE)) { set.seed(82) d <- data.frame(x = runif(100), z = runif(100)) d$y <- sin(6 * d$x) + rnorm(100, sd = exp(0.3 * d$z)) m <- GJRM::gamlss(list(y ~ s(x, k = 4), ~ s(z, k = 4)), data = d) estimates <- smooth_estimates(m, n = 50) draw(estimates) } # parallel processing of smooths if (requireNamespace("mirai") && requireNamespace("carrier")) { library("mirai") daemons(2) # only low for CRAN requirements smooth_estimates(m1) }
The label 'mgcv' uses for smooths is useful in many contexts, including
selecting smooths or labelling plots. smooth_label() extracts this label
from an 'mgcv' smooth object, i.e. an object that inherits from class
"mgcv.smooth". These would typically be found in the $smooth component of
a GAM fitted by mgcv::gam() or mgcv::bam(), or related functions.
## S3 method for class 'gamm4' smooth_label(object, id, ...) smooth_label(object, ...) ## S3 method for class 'gam' smooth_label(object, id, ...) ## S3 method for class 'mgcv.smooth' smooth_label(object, ...)## S3 method for class 'gamm4' smooth_label(object, id, ...) smooth_label(object, ...) ## S3 method for class 'gam' smooth_label(object, id, ...) ## S3 method for class 'mgcv.smooth' smooth_label(object, ...)
object |
an R object. Currently, methods for class |
id |
numeric; the indices of the smooths whose labels are to be extracted. If missing, labels for all smooths in the model are returned. |
... |
arguments passed to other methods. |
A character vector.
load_mgcv() df <- data_sim("gwf2", n = 100) m <- gam(y ~ s(x), data = df, method = "REML") # extract the smooth sm <- get_smooths_by_id(m, id = 1)[[1]] # extract the label smooth_label(sm) # or directly on the fitted GAM smooth_label(m$smooth[[1]]) # or extract labels by idex/position smooth_label(m, id = 1)load_mgcv() df <- data_sim("gwf2", n = 100) m <- gam(y ~ s(x), data = df, method = "REML") # extract the smooth sm <- get_smooths_by_id(m, id = 1)[[1]] # extract the label smooth_label(sm) # or directly on the fitted GAM smooth_label(m$smooth[[1]]) # or extract labels by idex/position smooth_label(m, id = 1)
Returns draws from the posterior distributions of smooth functions in a GAM. Useful, for example, for visualising the uncertainty in individual estimated functions.
## S3 method for class 'gamm4' smooth_samples(model, ...) smooth_samples(model, ...) ## S3 method for class 'gam' smooth_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, select = NULL, n_grid = 200L, partial_match = NULL, envir = NULL )## S3 method for class 'gamm4' smooth_samples(model, ...) smooth_samples(model, ...) ## S3 method for class 'gam' smooth_samples( model, ..., data = NULL, n_draws = NULL, chains = NULL, seed = NULL, method = c("gaussian", "mh", "inla", "user"), n_cores = 1L, n_threads = 1L, burnin = 1000, thin = 1L, t_df = 40, rw_scale = 0.25, frequentist = FALSE, unconditional = FALSE, draws = NULL, diagnostics = FALSE, mh_backend = c("mgcv", "gratia", "family"), mvn_method = c("mvnfast", "mgcv"), block_size = 10000L, dense_limit = 5e+06, select = NULL, n_grid = 200L, partial_match = NULL, envir = NULL )
model |
a fitted model of the supported types; see diagnostic_support. |
... |
arguments passed to other methods. For |
data |
data frame; new observations at which the posterior draws
from the model should be evaluated. If not supplied, the data used to fit
the model will be used for |
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
chains |
positive integer or |
seed |
numeric; a random seed for the simulations. |
method |
character; which method should be used to draw samples from
the posterior distribution. |
n_cores |
positive integer; maximum concurrent MH chains using mirai,
capped at |
n_threads |
positive integer; threads within Gaussian sampling using mvnfast. Defaults to one. This is separate from concurrent MH chains. |
burnin |
numeric; number of samples to discard as the burnin draws.
Only used with |
thin |
positive integer; retain every |
t_df |
numeric; degrees of freedom for t distribution proposals. Only
used with |
rw_scale |
numeric; Factor by which to scale posterior covariance
matrix when generating random walk proposals. Negative or non finite to
skip the random walk step. Only used with |
frequentist |
logical; |
unconditional |
logical; if |
draws |
matrix; user supplied posterior draws to be used when
|
diagnostics |
logical; calculate coefficient R-hat, effective sample sizes, and Monte Carlo standard errors using the optional posterior package. |
mh_backend |
character; |
mvn_method |
character; one of |
block_size |
positive integer; maximum observation rows per block in the gratia MH evaluator. Large designs are evaluated without storing a full matrix. |
dense_limit |
numeric; maximum number of design-matrix elements to cache for the gratia MH backend. Use zero to force blockwise evaluation. |
select |
character; select which smooth's posterior to draw from.
The default ( |
n_grid |
positive integer; resolution for constructing evaluation data if
|
partial_match |
logical; should smooths be selected by partial matches
with |
envir |
an optional environment for looking up data, functions and constants. Defaults to the model's evaluation environment. |
For LSS models, each smooth is a contribution to its own linear predictor.
Select its full smooth label to distinguish predictors, for example s(x)
and s.1(x). These are component draws on the predictor scale; use
fitted_samples() with quantity = "expectation" for the expected response
and derivative_samples() for
its derivative. Coefficients are drawn jointly across all predictors.
A tibble with additional classes "smooth_samples" and
'"posterior_samples".
For the "gam" method, the columns currently returned (not in this order)
are:
.smooth; character vector. Indicates the smooth function for that
particular draw,
.term; character vector. Similar to smooth, but will contain the
full label for the smooth, to differentiate factor-by smooths for
example.
.by; character vector. If the smooth involves a by term, the
by variable will be named here, NA_character_ otherwise.
.row; integer. A vector of values seq_len(nrow(data)), repeated if
n_draws > 1L. Indexes the row in data for that particular draw.
.draw; integer. A vector of integer values indexing the particular
posterior draw that each row belongs to.
.value; numeric. The value of smooth function for this posterior draw
and covariate combination.
xxx; numeric. A series of one or more columns containing data required
for the smooth, named as per the variables involved in the respective
smooth.
Additional columns will be present in the case of factor by smooths,
which will contain the level for the factor named in by_variable for
that particular posterior draw.
The set of variables returned and their order in the tibble is subject to change in future versions. Don't rely on position.
With mirai and carrier installed, configure workers with
mirai::daemons() to distribute calculations across selected smooths.
difference_smooths() distributes factor-level comparisons instead.
Without configured workers, or with only one calculation, evaluation is
serial. These functions leave the caller's worker pool running.
Model selection, evaluation of model expressions and random draws are
prepared in the caller. Workers receive the coordinates and coefficient
columns needed for their calculation. Custom prediction methods are evaluated
in the caller, including custom tensor margins and factor-smooth bases;
workers receive their prediction matrices. Simultaneous intervals use successive
draws in selection order, so set.seed() gives the same results with or
without workers, independently of their number or completion order.
derivatives() uses set.seed(); the other functions also accept seed,
which restores the caller's random number state on exit.
smooth_samples() draws coefficients jointly once, then reuses those draws
for every smooth, preserving dependence and chain identities. Sampling
finishes before smooth calculations start, so MH chains and smooth workers
are not nested. Sampling thread controls keep their existing meanings.
Workers use their configured BLAS thread settings; when using a threaded
BLAS, limit its threads before starting daemons to avoid competing threads.
Parallel work is most useful for expensive bases or interval calculations. Small grids can be slower because of transfer and scheduling costs. Large grids and many draws also require memory for worker inputs and returned results, in addition to the final output.
Gavin L. Simpson
load_mgcv() dat <- data_sim("eg1", n = 400, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") sms <- smooth_samples(m1, select = "s(x0)", n_draws = 5, seed = 42) sms ## A factor by example (with a spurious covariate x0) dat <- data_sim("eg4", n = 1000, seed = 2) ## fit model... m2 <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = dat) sms <- smooth_samples(m2, n_draws = 5, seed = 42) draw(sms)load_mgcv() dat <- data_sim("eg1", n = 400, seed = 2) m1 <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat, method = "REML") sms <- smooth_samples(m1, select = "s(x0)", n_draws = 5, seed = 42) sms ## A factor by example (with a spurious covariate x0) dat <- data_sim("eg4", n = 1000, seed = 2) ## fit model... m2 <- gam(y ~ fac + s(x2, by = fac) + s(x0), data = dat) sms <- smooth_samples(m2, n_draws = 5, seed = 42) draw(sms)
## S3 method for class 'gamm4' smooth_terms(object, ...) ## S3 method for class 'scam' smooth_terms(object, ...) smooth_terms(object, ...)## S3 method for class 'gamm4' smooth_terms(object, ...) ## S3 method for class 'scam' smooth_terms(object, ...) smooth_terms(object, ...)
object |
an R object the result of a call to |
... |
arguments passed to other methods. Currently unused. |
Soap-film boundary and wiggly components use the sf.film and sf.wiggly
classes introduced in mgcv 1.9-4.
B-spline tensor products (bs = "bt", available from mgcv 1.9-5) use
the short name "B spline tensor".
smooth_type(smooth) ## Default S3 method: smooth_type(smooth) ## S3 method for class 'tprs.smooth' smooth_type(smooth) ## S3 method for class 'ts.smooth' smooth_type(smooth) ## S3 method for class 'cr.smooth' smooth_type(smooth) ## S3 method for class 'cs.smooth' smooth_type(smooth) ## S3 method for class 'cyclic.smooth' smooth_type(smooth) ## S3 method for class 'pspline.smooth' smooth_type(smooth) ## S3 method for class 'cpspline.smooth' smooth_type(smooth) ## S3 method for class 'Bspline.smooth' smooth_type(smooth) ## S3 method for class 'b.tensor' smooth_type(smooth) ## S3 method for class 'duchon.spline' smooth_type(smooth) ## S3 method for class 'fs.interaction' smooth_type(smooth) ## S3 method for class 'sz.interaction' smooth_type(smooth) ## S3 method for class 'gp.smooth' smooth_type(smooth) ## S3 method for class 'mrf.smooth' smooth_type(smooth) ## S3 method for class 'random.effect' smooth_type(smooth) ## S3 method for class 'sf.wiggly' smooth_type(smooth) ## S3 method for class 'sf.film' smooth_type(smooth) ## S3 method for class 'soap.film' smooth_type(smooth) ## S3 method for class 't2.smooth' smooth_type(smooth) ## S3 method for class 'sos.smooth' smooth_type(smooth) ## S3 method for class 'tensor.smooth' smooth_type(smooth) ## S3 method for class 'mpi.smooth' smooth_type(smooth) ## S3 method for class 'mpd.smooth' smooth_type(smooth) ## S3 method for class 'cx.smooth' smooth_type(smooth) ## S3 method for class 'cv.smooth' smooth_type(smooth) ## S3 method for class 'micx.smooth' smooth_type(smooth) ## S3 method for class 'micv.smooth' smooth_type(smooth) ## S3 method for class 'mdcx.smooth' smooth_type(smooth) ## S3 method for class 'mdcv.smooth' smooth_type(smooth) ## S3 method for class 'miso.smooth' smooth_type(smooth) ## S3 method for class 'mifo.smooth' smooth_type(smooth) ## S3 method for class 'po.smooth' smooth_type(smooth) ## S3 method for class 'ipo.smooth' smooth_type(smooth) ## S3 method for class 'dpo.smooth' smooth_type(smooth) ## S3 method for class 'cpopspline.smooth' smooth_type(smooth) ## S3 method for class 'lmpi.smooth' smooth_type(smooth) ## S3 method for class 'lipl.smooth' smooth_type(smooth) ## S3 method for class 'tedmi.smooth' smooth_type(smooth) ## S3 method for class 'tedmd.smooth' smooth_type(smooth) ## S3 method for class 'tedi.smooth' smooth_type(smooth) ## S3 method for class 'teid.smooth' smooth_type(smooth) ## S3 method for class 'temicx.smooth' smooth_type(smooth) ## S3 method for class 'temicv.smooth' smooth_type(smooth) ## S3 method for class 'tedecx.smooth' smooth_type(smooth) ## S3 method for class 'tedecv.smooth' smooth_type(smooth) ## S3 method for class 'tecxcx.smooth' smooth_type(smooth) ## S3 method for class 'tecvcv.smooth' smooth_type(smooth) ## S3 method for class 'tecxcv.smooth' smooth_type(smooth) ## S3 method for class 'tesmi1.smooth' smooth_type(smooth) ## S3 method for class 'tesmi2.smooth' smooth_type(smooth) ## S3 method for class 'tesmd1.smooth' smooth_type(smooth) ## S3 method for class 'tesmd2.smooth' smooth_type(smooth) ## S3 method for class 'tescx.smooth' smooth_type(smooth) ## S3 method for class 'tescv.smooth' smooth_type(smooth) ## S3 method for class 'tismi.smooth' smooth_type(smooth) ## S3 method for class 'tismd.smooth' smooth_type(smooth) ## S3 method for class 'mpiBy.smooth' smooth_type(smooth) ## S3 method for class 'mpdBy.smooth' smooth_type(smooth) ## S3 method for class 'cxBy.smooth' smooth_type(smooth) ## S3 method for class 'cvBy.smooth' smooth_type(smooth) ## S3 method for class 'micxBy.smooth' smooth_type(smooth) ## S3 method for class 'micvBy.smooth' smooth_type(smooth) ## S3 method for class 'mdcxBy.smooth' smooth_type(smooth) ## S3 method for class 'mdcvBy.smooth' smooth_type(smooth)smooth_type(smooth) ## Default S3 method: smooth_type(smooth) ## S3 method for class 'tprs.smooth' smooth_type(smooth) ## S3 method for class 'ts.smooth' smooth_type(smooth) ## S3 method for class 'cr.smooth' smooth_type(smooth) ## S3 method for class 'cs.smooth' smooth_type(smooth) ## S3 method for class 'cyclic.smooth' smooth_type(smooth) ## S3 method for class 'pspline.smooth' smooth_type(smooth) ## S3 method for class 'cpspline.smooth' smooth_type(smooth) ## S3 method for class 'Bspline.smooth' smooth_type(smooth) ## S3 method for class 'b.tensor' smooth_type(smooth) ## S3 method for class 'duchon.spline' smooth_type(smooth) ## S3 method for class 'fs.interaction' smooth_type(smooth) ## S3 method for class 'sz.interaction' smooth_type(smooth) ## S3 method for class 'gp.smooth' smooth_type(smooth) ## S3 method for class 'mrf.smooth' smooth_type(smooth) ## S3 method for class 'random.effect' smooth_type(smooth) ## S3 method for class 'sf.wiggly' smooth_type(smooth) ## S3 method for class 'sf.film' smooth_type(smooth) ## S3 method for class 'soap.film' smooth_type(smooth) ## S3 method for class 't2.smooth' smooth_type(smooth) ## S3 method for class 'sos.smooth' smooth_type(smooth) ## S3 method for class 'tensor.smooth' smooth_type(smooth) ## S3 method for class 'mpi.smooth' smooth_type(smooth) ## S3 method for class 'mpd.smooth' smooth_type(smooth) ## S3 method for class 'cx.smooth' smooth_type(smooth) ## S3 method for class 'cv.smooth' smooth_type(smooth) ## S3 method for class 'micx.smooth' smooth_type(smooth) ## S3 method for class 'micv.smooth' smooth_type(smooth) ## S3 method for class 'mdcx.smooth' smooth_type(smooth) ## S3 method for class 'mdcv.smooth' smooth_type(smooth) ## S3 method for class 'miso.smooth' smooth_type(smooth) ## S3 method for class 'mifo.smooth' smooth_type(smooth) ## S3 method for class 'po.smooth' smooth_type(smooth) ## S3 method for class 'ipo.smooth' smooth_type(smooth) ## S3 method for class 'dpo.smooth' smooth_type(smooth) ## S3 method for class 'cpopspline.smooth' smooth_type(smooth) ## S3 method for class 'lmpi.smooth' smooth_type(smooth) ## S3 method for class 'lipl.smooth' smooth_type(smooth) ## S3 method for class 'tedmi.smooth' smooth_type(smooth) ## S3 method for class 'tedmd.smooth' smooth_type(smooth) ## S3 method for class 'tedi.smooth' smooth_type(smooth) ## S3 method for class 'teid.smooth' smooth_type(smooth) ## S3 method for class 'temicx.smooth' smooth_type(smooth) ## S3 method for class 'temicv.smooth' smooth_type(smooth) ## S3 method for class 'tedecx.smooth' smooth_type(smooth) ## S3 method for class 'tedecv.smooth' smooth_type(smooth) ## S3 method for class 'tecxcx.smooth' smooth_type(smooth) ## S3 method for class 'tecvcv.smooth' smooth_type(smooth) ## S3 method for class 'tecxcv.smooth' smooth_type(smooth) ## S3 method for class 'tesmi1.smooth' smooth_type(smooth) ## S3 method for class 'tesmi2.smooth' smooth_type(smooth) ## S3 method for class 'tesmd1.smooth' smooth_type(smooth) ## S3 method for class 'tesmd2.smooth' smooth_type(smooth) ## S3 method for class 'tescx.smooth' smooth_type(smooth) ## S3 method for class 'tescv.smooth' smooth_type(smooth) ## S3 method for class 'tismi.smooth' smooth_type(smooth) ## S3 method for class 'tismd.smooth' smooth_type(smooth) ## S3 method for class 'mpiBy.smooth' smooth_type(smooth) ## S3 method for class 'mpdBy.smooth' smooth_type(smooth) ## S3 method for class 'cxBy.smooth' smooth_type(smooth) ## S3 method for class 'cvBy.smooth' smooth_type(smooth) ## S3 method for class 'micxBy.smooth' smooth_type(smooth) ## S3 method for class 'micvBy.smooth' smooth_type(smooth) ## S3 method for class 'mdcxBy.smooth' smooth_type(smooth) ## S3 method for class 'mdcvBy.smooth' smooth_type(smooth)
smooth |
an object inheriting from class |
SCAM smooth types use compact constraint descriptions: inc for
increasing, dec for decreasing, and pos for positive. For tensor
smooths, the two descriptions follow the covariate order in the smooth
specification; free denotes an unconstrained direction. Tensor int.
identifies an interaction. Explicit By bases share the type label of
the corresponding ordinary basis.
Names of smooths in a GAM
## S3 method for class 'gamlss' smooths(object, ...) ## S3 method for class 'gjrm' smooths(object, ...) smooths(object, ...) ## Default S3 method: smooths(object, ...) ## S3 method for class 'gamm' smooths(object, ...) ## S3 method for class 'gamm4' smooths(object, ...)## S3 method for class 'gamlss' smooths(object, ...) ## S3 method for class 'gjrm' smooths(object, ...) smooths(object, ...) ## Default S3 method: smooths(object, ...) ## S3 method for class 'gamm' smooths(object, ...) ## S3 method for class 'gamm4' smooths(object, ...)
object |
a fitted GAM or related model. Typically the result of a call
to |
... |
Arguments passed to methods. |
For GJRM models, labels follow equation and smooth order.
Labels repeated in later equations receive suffixes such as s.1(x).
These labels can be supplied to draw() or smooth_estimates() to select
smooths across equations.
Evaluate a spline at provided covariate values
spline_values( smooth, data, model, unconditional, overall_uncertainty = TRUE, frequentist = FALSE, envir = NULL )spline_values( smooth, data, model, unconditional, overall_uncertainty = TRUE, frequentist = FALSE, envir = NULL )
smooth |
currently an object that inherits from class |
data |
a data frame of values to evaluate |
model |
a fitted model; currently only |
unconditional |
logical; if |
overall_uncertainty |
logical; should the uncertainty in the model constant term be included in the standard error of the evaluate values of the smooth? |
frequentist |
logical; if |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
Draw continuous residuals for models fitted with mgcv::ocat() or
mgcv::multinom(), using the latent-variable methods of Liu and Zhang
(2018) and Cheng, Wang and Zhang (2021). No additional package is required.
surrogate_residuals(model, seed = NULL, ...) ## S3 method for class 'gam' surrogate_residuals(model, seed = NULL, conditioning = NULL, ...) ## Default S3 method: surrogate_residuals(model, seed = NULL, ...)surrogate_residuals(model, seed = NULL, ...) ## S3 method for class 'gam' surrogate_residuals(model, seed = NULL, conditioning = NULL, ...) ## Default S3 method: surrogate_residuals(model, seed = NULL, ...)
model |
a fitted model object. |
seed |
integer or |
... |
arguments passed to other methods. |
conditioning |
character or |
An ordered categorical model represents category j by an interval between
two thresholds on a continuous latent scale. For each observation, a surrogate
response is drawn from the fitted logistic distribution restricted to its
observed category's interval. The residual subtracts the fitted latent mean
from this surrogate response.
Equivalently, draw a probability uniformly between the fitted probabilities
Pr(Y < y) and Pr(Y <= y), then apply stats::qlogis(). Under the assumed
model with known parameters, the residuals have a logistic distribution with
location zero and scale one: mean zero and variance pi^2 / 3. Fitted
parameters affect this reference approximation. The identity link reported by
ocat() describes the latent mean; its latent distribution is logistic.
This calculation shares the randomised probabilities used by
quantile_residuals(), which instead applies qnorm() for normal scores.
Both tails are calculated using log probabilities to retain accuracy when
ordinary probabilities round to zero or one. Fitting weights do not change
the scale of the latent logistic distribution.
For a nominal multinomial response, there is a utility for every category,
including category 0. Its fitted locations are (0, eta_1, ..., eta_K),
including offsets and fitted random effects, with independent standard
Gumbel errors having CDF exp(-exp(-x)). Draw the complete utility vector
conditional on the observed category being its maximum. Subtract each
location and Euler's constant (-digamma(1)) to obtain the residual vector.
Under the known-parameter model, each component has a centred Gumbel
reference with mean zero and variance pi^2 / 6; the joint null consists
of independent centred Gumbel components. The conditional draw given an
observed category preserves dependence among its utilities. Differences
from the reference utility would have dependent logistic marginals. Even
for K = 1, this function retains both Gumbel utility components.
The maximum has a Gumbel distribution with location equal to the log-sum-exp of the fitted locations, independently of the winning label. Conditional on that maximum and the observed winner, the other utilities have independent upper-truncated Gumbel distributions. The sampler uses this identity directly, with log calculations that retain accuracy for rare observed categories and extreme predictors, without rejection or Gibbs iterations. This construction does not impose an ordering on categories.
Supported fits are gam and bam models with a single ocat() family,
and gam models with multinom(). Grouped families and other model classes
are not supported. Fitted random effects are held fixed. Use
type = "surrogate" in appraise(), qq_plot(), worm_plot() and
residual plots. QQ and worm plots require method = NULL, with logistic
references for ocat() and centred Gumbel references for multinom().
Pointwise order-statistic bands apply separately to each utility component,
treating fitted parameters as fixed. They do not give simultaneous coverage
across categories. Components are always shown separately, including when
by_family = FALSE. For ocat(), residuals_linpred_plot() uses the fitted
latent mean. For multinom(), it uses each category's fitted probability;
observed-versus-fitted panels compare that probability with its category
indicator. This also gives category 0 a varying horizontal axis despite its
fixed utility location. Covariate plots separate the category utilities.
The ordered correlation helpers do not yet accept multinomial utilities.
Ordinary and scalable plots use exactly the same conditional draw for a
given seed. appraise() reuses one draw across all its panels. Scalable
plots retain the residual matrix and process one component at a time before
combining display summaries; observations, rather than utility components,
determine automatic dispatch thresholds. Changing sampler chunk sizes does
not change the draw. QQ binning and density grids change only the display.
Each call draws one residual vector per observation. Set seed for
reproducibility;
repeating plots with different seeds helps assess whether a pattern persists
across residual draws. An explicit seed preserves the caller's random-number
state. With seed = NULL, sampling uses and advances the current state.
For ocat(), a numeric vector with one residual per observation.
For multinom(K), a numeric matrix with one row per observation and K+1
columns named "0", ..., "K", identifying the category utilities.
With na.exclude, excluded fitting rows are restored as NA; with
na.omit, only observations used for fitting are returned.
Cheng, C., Wang, R. and Zhang, H. (2021). Surrogate Residuals for Discrete Choice Models. Journal of Computational and Graphical Statistics, 30(1), 67–77. doi:10.1080/10618600.2020.1775618.
Liu, D. and Zhang, H. (2018). Residuals and Diagnostics for Ordinal Regression Models: A Surrogate Approach. Journal of the American Statistical Association, 113(522), 845–854. doi:10.1080/01621459.2017.1292915.
quantile_residuals(), appraise(), diagnostic_support
load_mgcv() set.seed(359) dat <- data.frame(x = runif(200, -2, 2)) latent <- sin(dat$x) + rlogis(nrow(dat)) dat$y <- findInterval(latent, c(-1, 0, 2)) + 1L fit <- gam(y ~ s(x), data = dat, family = ocat(R = 4), method = "REML") head(surrogate_residuals(fit, seed = 42)) appraise(fit, type = "surrogate", seed = 42)load_mgcv() set.seed(359) dat <- data.frame(x = runif(200, -2, 2)) latent <- sin(dat$x) + rlogis(nrow(dat)) dat$y <- findInterval(latent, c(-1, 0, 2)) + 1L fit <- gam(y ~ s(x), data = dat, family = ocat(R = 4), method = "REML") head(surrogate_residuals(fit, seed = 42)) appraise(fit, type = "surrogate", seed = 42)
Extract names of all variables needed to fit a GAM or a smooth
## S3 method for class 'gamm4' term_names(object, ...) ## S3 method for class 'scam' term_names(object, ...) term_names(object, ...) ## S3 method for class 'gam' term_names(object, ...) ## S3 method for class 'mgcv.smooth' term_names(object, ...) ## S3 method for class 'gamm' term_names(object, ...)## S3 method for class 'gamm4' term_names(object, ...) ## S3 method for class 'scam' term_names(object, ...) term_names(object, ...) ## S3 method for class 'gam' term_names(object, ...) ## S3 method for class 'mgcv.smooth' term_names(object, ...) ## S3 method for class 'gamm' term_names(object, ...)
object |
a fitted GAM object (inheriting from class |
... |
arguments passed to other methods. Not currently used. |
A vector of variable names required for terms in the model
Given the name (a term label) of a term in a model, returns the names of the variables involved in the term.
## S3 method for class 'gamm4' term_variables(object, ...) ## S3 method for class 'scam' term_variables(object, term, ...) term_variables(object, term, ...) ## S3 method for class 'terms' term_variables(object, term, ...) ## S3 method for class 'gam' term_variables(object, term, ...) ## S3 method for class 'bam' term_variables(object, term, ...)## S3 method for class 'gamm4' term_variables(object, ...) ## S3 method for class 'scam' term_variables(object, term, ...) term_variables(object, term, ...) ## S3 method for class 'terms' term_variables(object, term, ...) ## S3 method for class 'gam' term_variables(object, term, ...) ## S3 method for class 'bam' term_variables(object, term, ...)
object |
an R object on which method dispatch is performed |
... |
arguments passed to other methods. |
term |
character; the name of a model term, in the sense of
|
A character vector of variable names.
General extractor for additional parameters in mgcv models
theta(object, ...) ## S3 method for class 'gam' theta(object, transform = TRUE, ...) ## S3 method for class 'family' theta(object, transform = TRUE, ...) ## S3 method for class 'gamm4' theta(object, ...)theta(object, ...) ## S3 method for class 'gam' theta(object, transform = TRUE, ...) ## S3 method for class 'family' theta(object, transform = TRUE, ...) ## S3 method for class 'gamm4' theta(object, ...)
object |
a fitted model |
... |
arguments passed to other methods. |
transform |
logical; transform to the natural scale of the parameter |
Returns a numeric vector of additional parameters
load_mgcv() df <- data_sim("eg1", dist = "poisson", seed = 42, scale = 1 / 5) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML", family = nb() ) p <- theta(m)load_mgcv() df <- data_sim("eg1", dist = "poisson", seed = 42, scale = 1 / 5) m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML", family = nb() ) p <- theta(m)
Takes an object of class mgcv.smooth and returns a tidy representation
of the basis.
tidy_basis( smooth, data = NULL, at = NULL, coefs = NULL, p_ident = NULL, envir = NULL )tidy_basis( smooth, data = NULL, at = NULL, coefs = NULL, p_ident = NULL, envir = NULL )
smooth |
a smooth object of or inheriting from class |
data |
a data frame containing the variables used in |
at |
a data frame containing values of the smooth covariate(s) at which the basis should be evaluated. |
coefs |
numeric; an optional vector of coefficients for the smooth |
p_ident |
retained for compatibility. Fitted SCAM smooths use their stored coefficient constraints to match basis columns to coefficients. |
envir |
an optional environment supplying functions and constants used
in model expressions. The available model formula environment is used when
|
A tibble.
Gavin L. Simpson
load_mgcv() df <- data_sim("eg1", n = 400, seed = 42) # fit model m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # tidy representaition of a basis for a smooth definition # extract the smooth sm <- get_smooth(m, "s(x2)") # get the tidy basis - need to pass where we want it to be evaluated bf <- tidy_basis(sm, at = df) # can weight the basis by the model coefficients for this smooth bf <- tidy_basis(sm, at = df, coefs = smooth_coefs(sm, model = m))load_mgcv() df <- data_sim("eg1", n = 400, seed = 42) # fit model m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") # tidy representaition of a basis for a smooth definition # extract the smooth sm <- get_smooth(m, "s(x2)") # get the tidy basis - need to pass where we want it to be evaluated bf <- tidy_basis(sm, at = df) # can weight the basis by the model coefficients for this smooth bf <- tidy_basis(sm, at = df, coefs = smooth_coefs(sm, model = m))
NA
Given a vector i indexing the elements of x, sets the selected elements
of x to NA.
to_na(x, i)to_na(x, i)
x |
vector of values |
i |
vector of values used to subset |
Returns x with possibly some elements set to NA
Identifies pairs of covariate values that lie too far from the original data.
The function is currently a basic wrapper around mgcv::exclude.too.far().
too_far(x, y, ref_1, ref_2, dist = NULL)too_far(x, y, ref_1, ref_2, dist = NULL)
x, y
|
numeric; vector of values of the covariates to compare with the observed data |
ref_1, ref_2
|
numeric; vectors of covariate values that represent the
reference against which |
dist |
if supplied, a numeric vector of length 1 representing the
distance from the data beyond which an observation is excluded. For
example, you want to exclude values that lie further from an observation
than 10% of the range of the observed data, use |
Returns a logical vector of the same length as x1.
NA if the lie too far from a reference set of valuesSet rows of data to NA if the lie too far from a reference set of values
too_far_to_na(smooth, input, reference, cols, dist = NULL)too_far_to_na(smooth, input, reference, cols, dist = NULL)
smooth |
an mgcv smooth object |
input |
data frame containing the input observations and the columns to
be set to |
reference |
data frame containing the reference values |
cols |
character vector of columns whose elements will be set to |
dist |
numeric, the distance from the reference set beyond which
elements of |
Transform estimated values and confidence intervals by applying a function
transform_fun(object, fun = NULL, ...) ## S3 method for class 'smooth_estimates' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'smooth_samples' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'mgcv_smooth' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'evaluated_parametric_term' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'parametric_effects' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'tbl_df' transform_fun(object, fun = NULL, column = NULL, constant = NULL, ...)transform_fun(object, fun = NULL, ...) ## S3 method for class 'smooth_estimates' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'smooth_samples' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'mgcv_smooth' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'evaluated_parametric_term' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'parametric_effects' transform_fun(object, fun = NULL, constant = NULL, ...) ## S3 method for class 'tbl_df' transform_fun(object, fun = NULL, column = NULL, constant = NULL, ...)
object |
an object to apply the transform function to. |
fun |
the function to apply. |
... |
additional arguments passed to methods. |
constant |
numeric; a constant to apply before transformation. |
column |
character; for the |
Returns object but with the estimate and upper and lower values
of the confidence interval transformed via the function.
Gavin L. Simpson
Typical values of model covariates
typical_values(object, ...) ## S3 method for class 'gam' typical_values(object, vars = everything(), data = NULL, ...) ## S3 method for class 'data.frame' typical_values(object, vars = everything(), ...) ## S3 method for class 'gamm4' typical_values(object, ...)typical_values(object, ...) ## S3 method for class 'gam' typical_values(object, vars = everything(), data = NULL, ...) ## S3 method for class 'data.frame' typical_values(object, vars = everything(), ...) ## S3 method for class 'gamm4' typical_values(object, ...)
object |
a fitted GAM(M) model. |
... |
arguments passed to other methods. |
vars |
terms to include or exclude from the returned object. Uses tidyselect principles. |
data |
an optional data frame supplying covariate classes. By default, these are taken from the stored model frame; typical values come from the fitted model's covariate summaries. |
Handle user-supplied posterior draws
## S3 method for class 'gamm4' user_draws(model, ..., draws, n_draws = NULL, chains = NULL) user_draws(model, ..., draws) ## S3 method for class 'gam' user_draws(model, ..., n_draws = NULL, chains = NULL, draws, index = NULL) ## S3 method for class 'scam' user_draws( model, ..., draws = NULL, n_draws = NULL, chains = NULL, index = NULL )## S3 method for class 'gamm4' user_draws(model, ..., draws, n_draws = NULL, chains = NULL) user_draws(model, ..., draws) ## S3 method for class 'gam' user_draws(model, ..., n_draws = NULL, chains = NULL, draws, index = NULL) ## S3 method for class 'scam' user_draws( model, ..., draws = NULL, n_draws = NULL, chains = NULL, index = NULL )
model |
a fitted model from |
... |
arguments passed to methods. |
draws |
matrix; user supplied posterior draws to be used when
|
n_draws |
positive integer; total retained draws across all chains.
Required when generating draws. With |
chains |
positive integer or |
index |
a vector to index (subset) the columns of |
The supplied draws must be a matrix (currently), with 1 column per
model coefficient, and 1 row per posterior draw. The "gam" method has
argument index, which can be used to subset (select) coefficients
(columns) of draws. index can be any valid way of selecting (indexing)
columns of a matrix. index is useful if you have a set of posterior draws
for the entire model (say from mgcv::gam.mh()) and you wish to use those
draws for an individual smooth, via smooth_samples().
For SCAM models, supplied draws must contain finite transformed
coefficients in the order returned by coef(model). If column names are
supplied they must match exactly. Entries identified by model$p.ident
must be nonnegative. Draws returned with parametrized = FALSE cannot be
supplied directly for prediction; transform them first.
Extract variance components for smooth penalties and random effects, or calculate the variances and covariances of fitted term contributions.
## S3 method for class 'gamm4' variance_comp( object, rescale = TRUE, coverage = 0.95, interval_method = c("profile", "none"), type = c("penalty", "terms"), n_draws = 1000L, seed = NULL, unconditional = FALSE, include_total = TRUE, ... ) ## S3 method for class 'scam' variance_comp( object, rescale = TRUE, coverage = 0.95, type = c("penalty", "terms"), n_draws = 1000L, seed = NULL, unconditional = FALSE, include_total = TRUE, ... ) variance_comp(object, ...) ## S3 method for class 'gam' variance_comp( object, rescale = TRUE, coverage = 0.95, type = c("penalty", "terms"), n_draws = 1000L, seed = NULL, unconditional = FALSE, include_total = TRUE, ... ) ## S3 method for class 'gamm' variance_comp( object, rescale = TRUE, coverage = 0.95, type = c("penalty", "terms"), n_draws = 1000L, seed = NULL, unconditional = FALSE, include_total = TRUE, ... )## S3 method for class 'gamm4' variance_comp( object, rescale = TRUE, coverage = 0.95, interval_method = c("profile", "none"), type = c("penalty", "terms"), n_draws = 1000L, seed = NULL, unconditional = FALSE, include_total = TRUE, ... ) ## S3 method for class 'scam' variance_comp( object, rescale = TRUE, coverage = 0.95, type = c("penalty", "terms"), n_draws = 1000L, seed = NULL, unconditional = FALSE, include_total = TRUE, ... ) variance_comp(object, ...) ## S3 method for class 'gam' variance_comp( object, rescale = TRUE, coverage = 0.95, type = c("penalty", "terms"), n_draws = 1000L, seed = NULL, unconditional = FALSE, include_total = TRUE, ... ) ## S3 method for class 'gamm' variance_comp( object, rescale = TRUE, coverage = 0.95, type = c("penalty", "terms"), n_draws = 1000L, seed = NULL, unconditional = FALSE, include_total = TRUE, ... )
object |
a model fitted by |
rescale |
logical; for numerical stability reasons the penalty matrices
of smooths are rescaled before fitting. If |
coverage |
numeric; a value between 0 and 1 indicating the (approximate) coverage of the confidence interval that is returned. |
interval_method |
character; for |
type |
character; |
n_draws |
integer; number of joint posterior coefficient draws for
|
seed |
optional random seed for term intervals. Supplying a seed preserves the caller's random-number state. |
unconditional |
logical; include the available correction for
smoothing-parameter uncertainty in term intervals. Defaults to |
include_total |
logical; include total rows for |
... |
arguments passed to other methods. For |
For SCAM fits with type = "penalty", .variance is the fitted
response scale divided by
the smoothing parameter, optionally undoing penalty rescaling. This ratio
describes the Gaussian penalty on unrestricted fitting parameters; it is
not a Gaussian variance for the transformed smooth coefficients. SCAM's
GCV and UBRE fits do not supply the likelihood-based smoothing-parameter
covariance needed for confidence limits, so both limit columns are NA.
With type = "penalty", models fitted by mgcv::gam() and
mgcv::bam() have one row per penalty, including penalties supplied through
paraPen.
Fixed smoothing parameters are included, and terms sharing a smoothing
parameter each have their own rows. A smooth with several penalties has
several rows. Unpenalized parametric terms have no variance parameter and
are omitted.
The variance component is the fitted scale parameter divided by the
smoothing parameter. With rescale = TRUE, the smoothing parameter is
first divided by the penalty's scaling factor. These components describe
the penalty on coefficients, rather than the variation in fitted term
values over the observations.
Confidence intervals use the Hessian of the likelihood-based smoothness
selection criterion, transformed to the log standard deviation scale.
Shared smoothing parameters retain their shared uncertainty. A fixed
smoothing parameter can still have an interval when the model scale is
estimated. The scale is included as a separate row when its uncertainty is
available. Unavailable intervals are NA.
For mgcv::gamm() fits, components are extracted from lme. Smooth
variances are expressed on the same penalty scale as for gam() and
bam(), with one row per penalty. Additional random effects have one row
per coefficient variance, labelled by grouping factor and coefficient;
their covariances are omitted. Intervals use nlme::intervals() when the
fitted covariance parameters support this calculation. Bounds are NA
when that information is unavailable, including fits containing pdTens
tensor-product blocks. The estimated residual scale is labelled scale;
a fixed scale is omitted. With residual variance weights, scale is the
baseline variance before those weights are applied. For models fitted by
penalized quasi-likelihood (PQL), these are approximate components of the
working mixed model.
For gamm4::gamm4() fits, components are extracted from mer. Smooth
components use the same penalty scale and labels as the other methods;
additional random effects retain their mixed-model variances. By default,
intervals are computed separately for each standard deviation using
stats::profile() and stats::confint(). The profiling uses the fitted
random-effects design matrices. Gaussian models are refitted by maximum
likelihood for these profiles, including models fitted by REML; the
reported point estimates remain those of the original fit. Profiling can
take substantially longer than extracting estimates. Use
interval_method = "none" for estimates without intervals. Failed profiles
warn and return NA bounds for the affected component. Profiles are
unavailable for generalized mixed models with an estimated scale.
With type = "terms", each component is a fitted term's contribution to
the linear predictor, evaluated over the observations used to fit the model.
Parametric formula terms are included, with all coefficients of a factor,
polynomial or interaction combined into one term. Each smooth has one row,
including smooths with several penalties. Additional random effects in
gamm() and gamm4() contribute one component per grouping factor and
coefficient, evaluated at their fitted values. Formula terms follow the
model's contrast coding. Duplicated component labels receive numeric suffixes.
Term variances and covariances use equal observation weights and the sample
denominator, the number of fitting observations minus one. Likelihood
weights do not change this averaging. Intercepts, offsets and residual
variation are excluded. rescale and interval_method apply only to
type = "penalty"; no profiling is performed for term variances.
A final row labelled total gives the variance of the sum of the term
contributions, including additional fitted random effects. It includes
covariance between terms: the total is the sum of all entries of their
covariance matrix, rather than just its diagonal. Models with several linear
predictors have one total per predictor, labelled total, total.1, and
so on in predictor order. A term shared by several predictors contributes
to each of their totals. An intercept-only predictor has total variance zero.
These labels are reserved; a formula term with the same name receives a
numeric suffix so it remains distinct from the total.
Use include_total = FALSE to omit the total rows and their columns in
the posterior draw matrices. Totals are still calculated for proportions;
the individual term estimates and intervals are unchanged.
Proportions allocate the total variance using
Each term receives its own variance plus its covariance with the other terms. This splits each pair's covariance contribution equally between its two terms, so the individual proportions sum to one. Proportions can be negative or greater than one when terms offset each other's variation; they are not restricted to the interval from zero to one.
.proportion reports these allocations, with equal-tailed posterior bounds
in .proportion_lower_ci and .proportion_upper_ci. These bounds are on the
proportion scale. Each posterior proportion uses the term contributions
and total from the same joint draw. Individual interval limits need not sum
to one. The total row's proportion is one. For additional linear predictors,
the columns receive suffixes .1, .2, and so on, matching the total labels;
for example, .proportion.1 and .proportion_lower_ci.1. A shared term has a
separate allocation for each predictor. Entries for unrelated terms and
totals are NA.
Proportions are undefined when the total variance is zero and are returned
as NA, including for an intercept-only predictor. Posterior draws with
zero total variance retain NA proportions and are omitted when computing
proportion intervals; if none are defined, both bounds are NA.
Term intervals are equal-tailed posterior intervals, computed by drawing the
full coefficient vector from its approximate Gaussian posterior and
recalculating each term's variance over the same fitting observations.
All terms use the same coefficient draw in each replicate, preserving their
dependence. Each total is calculated by summing the term contributions
within that draw and then computing their variance. Additional fitted random
effects in mixed models are drawn
conditional on the GAM coefficients, retaining their covariance with the
GAM terms and with each other. Smoothing parameters, random-effect covariance
parameters and the response scale are held at their fitted values, unless
unconditional = TRUE supplies a correction for smoothing-parameter
uncertainty in the GAM coefficient covariance. PQL and generalized mixed
models use the Gaussian approximation at the fitted working model.
For SCAM fits, draws are made jointly on the unrestricted fitting scale
and transformed before evaluating the terms.
Point estimates remain the variances of the fitted contributions. Interval
bounds are quantiles of the posterior term standard deviations; square the
bounds to obtain intervals for the term variances. Use seed for reproducible
draws and n_draws = 0 to skip intervals and return NA bounds.
The covariance attribute contains the covariance matrix of the fitted
term contributions, with rows and columns in .component order, excluding
the total rows. Its diagonal equals .variance for the individual terms.
For a model with a single linear predictor, the sum of all matrix entries
equals the total row's .variance.
Adding only the diagonal omits covariance between terms. This matrix
describes variation across observations, rather than estimation uncertainty.
When intervals are computed, the variance_draws attribute contains a matrix
with one row per posterior draw and one column per component, on the variance
scale. Rows are paired across terms. Its column names match .component;
the coverage attribute records the requested interval coverage. The total
columns include covariance between term contributions within each draw.
Summing the individual term variances would omit that covariance.
The proportion_draws attribute is a named list with one matrix per total
(total, total.1, and so on). Each matrix has the same rows and columns as
variance_draws, with NA entries for unrelated components. Its rows retain
the pairing with the coefficient and variance draws. Proportions and their
intervals are added only for type = "terms".
The term_groups attribute lists the component labels belonging to each
predictor, named by its total label. Use draw.variance_comp() to plot
components or proportions with their stored intervals.
A tibble of class variance_comp, with .component, .variance,
.std_dev, .lower_ci and .upper_ci. Both confidence limits are on
the standard deviation scale. For type = "terms", obtain the named
covariance matrix with attr(result, "covariance") and posterior variance
draws with attr(result, "variance_draws") when intervals were computed.
Term results also include proportion estimates and their interval columns;
attr(result, "proportion_draws") contains the paired posterior proportions.
mgcv::gam.vcomp(), draw.variance_comp()
Returns names of variables from a smooth label
vars_from_label(label)vars_from_label(label)
label |
character; a length 1 character vector containing the label of a smooth. |
vars_from_label("s(x1)") vars_from_label("t2(x1,x2,x3)")vars_from_label("s(x1)") vars_from_label("t2(x1,x2,x3)")
Identify a smooth term by its label
## S3 method for class 'gamm4' which_smooths(object, ...) ## S3 method for class 'scam' which_smooths(object, terms, ...) which_smooths(object, ...) ## Default S3 method: which_smooths(object, ...) ## S3 method for class 'gam' which_smooths(object, terms, ...) ## S3 method for class 'bam' which_smooths(object, terms, ...) ## S3 method for class 'gamm' which_smooths(object, terms, ...)## S3 method for class 'gamm4' which_smooths(object, ...) ## S3 method for class 'scam' which_smooths(object, terms, ...) which_smooths(object, ...) ## Default S3 method: which_smooths(object, ...) ## S3 method for class 'gam' which_smooths(object, terms, ...) ## S3 method for class 'bam' which_smooths(object, terms, ...) ## S3 method for class 'gamm' which_smooths(object, terms, ...)
object |
a fitted GAM. |
... |
arguments passed to other methods. |
terms |
character; one or more (partial) term labels with which to identify required smooths. |
Worm plot of model residuals
worm_plot(model, ...) ## S3 method for class 'gam' worm_plot( model, method = NULL, type = NULL, n_uniform = 10, n_simulate = 50, level = 0.9, ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, ci_col = "black", ci_alpha = 0.2, point_col = "grey20", point_alpha = 1, line_col = "red", seed = NULL, by_family = NULL, conditioning = NULL, ..., n_dharma = 250L ) ## S3 method for class 'glm' worm_plot(model, ...) ## S3 method for class 'lm' worm_plot(model, ...) ## S3 method for class 'gamm4' worm_plot(model, conditioning = NULL, ...) ## S3 method for class 'gjrm' worm_plot(model, ..., type = "quantile", seed = NULL, response = NULL) ## S3 method for class 'gamm' worm_plot(model, conditioning = NULL, ...) ## S3 method for class 'gratia_diagnostic_proxy' worm_plot(model, type = "quantile", ...) ## S3 method for class 'lme' worm_plot(model, conditioning = NULL, ...) ## S3 method for class 'merMod' worm_plot(model, conditioning = NULL, ...) ## S3 method for class 'gamlss' worm_plot(model, ..., type = "quantile", seed = NULL) ## S3 method for class 'sdmTMB' worm_plot( model, conditioning = NULL, component = "response", field_method = c("mle-mvn", "mle-eb", "mle-mvn-integrated"), ... )worm_plot(model, ...) ## S3 method for class 'gam' worm_plot( model, method = NULL, type = NULL, n_uniform = 10, n_simulate = 50, level = 0.9, ylab = NULL, xlab = NULL, title = NULL, subtitle = NULL, caption = NULL, ci_col = "black", ci_alpha = 0.2, point_col = "grey20", point_alpha = 1, line_col = "red", seed = NULL, by_family = NULL, conditioning = NULL, ..., n_dharma = 250L ) ## S3 method for class 'glm' worm_plot(model, ...) ## S3 method for class 'lm' worm_plot(model, ...) ## S3 method for class 'gamm4' worm_plot(model, conditioning = NULL, ...) ## S3 method for class 'gjrm' worm_plot(model, ..., type = "quantile", seed = NULL, response = NULL) ## S3 method for class 'gamm' worm_plot(model, conditioning = NULL, ...) ## S3 method for class 'gratia_diagnostic_proxy' worm_plot(model, type = "quantile", ...) ## S3 method for class 'lme' worm_plot(model, conditioning = NULL, ...) ## S3 method for class 'merMod' worm_plot(model, conditioning = NULL, ...) ## S3 method for class 'gamlss' worm_plot(model, ..., type = "quantile", seed = NULL) ## S3 method for class 'sdmTMB' worm_plot( model, conditioning = NULL, component = "response", field_method = c("mle-mvn", "mle-eb", "mle-mvn-integrated"), ... )
model |
a fitted model supported by diagnostic_support. |
... |
arguments passed to other methods. |
method |
character or
For ordinary GAMs, |
type |
character or |
n_uniform |
numeric; number of inverse-CDF draws to average when
|
n_simulate |
numeric; number of data sets to simulate from the estimated
model when using the simulation method ( |
level |
numeric; the coverage level for reference intervals. Must be
strictly |
ylab |
character or expression; the label for the y axis. If not supplied, a suitable label will be generated. |
xlab |
character or expression; the label for the x axis. If not supplied, a suitable label will be generated. |
title |
character or expression; the title for the plot. See
|
subtitle |
character or expression; the subtitle for the plot. See
|
caption |
character or expression; the plot caption. See
|
ci_col |
Deprecated; use |
ci_alpha |
Deprecated; use |
point_col |
Deprecated; use |
point_alpha |
Deprecated; use |
line_col |
Deprecated; use |
seed |
numeric; the random number seed to use for |
by_family |
logical or |
conditioning |
character or |
n_dharma |
positive integer; number of response simulations for
|
response |
|
component |
character; for delta sdmTMB models, select the complete
|
field_method |
how to treat fitted sdmTMB fields: hold one posterior
draw fixed ( |
See appraise() for grouped-family defaults, supported distributions,
pooling and separate component panels. PIT and quantile residuals use fixed
uniform and standard-normal reference quantiles. For ideal independent
responses, bands are pointwise intervals for ordered residuals. For dependent
responses, bands use simulations that preserve dependence when available;
otherwise they are omitted. Residuals calculated from simulation ranks also
use simulated bands. See diagnostic_support for these choices and limits.
Bands condition on fitted parameters and exclude fitting uncertainty; they
do not provide simultaneous coverage. Traditional residuals use the fitted
response distributions or a normal approximation.
For mgcv::ocat() fits, type = "surrogate" uses logistic reference
quantiles with location zero and scale one. Set method = NULL. Independent
observations have approximate pointwise bands obtained by applying
qlogis() to beta order-statistic limits. Worm plots subtract the same
logistic reference quantiles from residuals and bands. These references
treat fitted parameters as fixed. For mgcv::multinom() GAMs, surrogate
residuals retain a utility component for every category, including 0.
Components have separate facets and centred Gumbel reference quantiles,
including when by_family = FALSE. The same reference is subtracted in
worm plots, and pointwise beta order-statistic bands use the centred
Gumbel quantile function separately for each component. Ordinary and
scalable displays share their draw. See surrogate_residuals().
Subtitles name the method. Captions identify conditioning and field choices,
joint simulation bands or omitted bands. Routine pointwise bands are unlabelled.
Supply caption to replace this text, or caption = "" to omit it.
Ordinary and scalable QQ and worm plots use the same labels.
The wording used in mgcv::qq.gam() uses direct in reference to the
simulated residuals method (method = "simulated"). To avoid confusion,
method = "direct" is deprecated in favour of method = "uniform".
load_mgcv() ## simulate binomial data... dat <- data_sim("eg1", n = 200, dist = "binary", scale = .33, seed = 0) p <- binomial()$linkinv(dat$f) # binomial p n <- sample(c(1, 3), 200, replace = TRUE) # binomial n dat <- transform(dat, y = rbinom(n, n, p), n = n) m <- gam(y / n ~ s(x0) + s(x1) + s(x2) + s(x3), family = binomial, data = dat, weights = n, method = "REML" ) ## The default uses inverse-CDF sampling of randomised uniform quantiles. ## Note no reference bands are drawn with this method. worm_plot(m) ## Alternatively simulate new data from the model, which ## allows construction of reference intervals for the Q-Q plot worm_plot(m, method = "simulate", point_col = "steelblue", point_alpha = 0.4 ) ## ... or request a normal approximation for the residuals. worm_plot(m, method = "normal")load_mgcv() ## simulate binomial data... dat <- data_sim("eg1", n = 200, dist = "binary", scale = .33, seed = 0) p <- binomial()$linkinv(dat$f) # binomial p n <- sample(c(1, 3), 200, replace = TRUE) # binomial n dat <- transform(dat, y = rbinom(n, n, p), n = n) m <- gam(y / n ~ s(x0) + s(x1) + s(x2) + s(x3), family = binomial, data = dat, weights = n, method = "REML" ) ## The default uses inverse-CDF sampling of randomised uniform quantiles. ## Note no reference bands are drawn with this method. worm_plot(m) ## Alternatively simulate new data from the model, which ## allows construction of reference intervals for the Q-Q plot worm_plot(m, method = "simulate", point_col = "steelblue", point_alpha = 0.4 ) ## ... or request a normal approximation for the residuals. worm_plot(m, method = "normal")
The Madison lake zooplankton data are from a long-term study in seasonal dynamics of zooplankton, collected by the Richard Lathrop. The data were collected from a chain of lakes in Wisconsin (Mendota, Monona, Kegnonsa, and Waubesa) approximately bi-weekly from 1976 to 1994. They consist of samples of the zooplankton communities, taken from the deepest point of each lake via vertical tow. The data are provided by the Wisconsin Department of Natural Resources and their collection and processing are fully described in Lathrop (2000).
A data frame
Each record consists of counts of a given zooplankton taxon taken from a subsample from a single vertical net tow, which was then scaled to account for the relative volume of subsample versus the whole net sample and the area of the net tow and rounded to the nearest 1000 to give estimated population density per m2 for each taxon at each point in time in each sampled lake.
Pedersen EJ, Miller DL, Simpson GL, Ross N. 2018. Hierarchical generalized additive models: an introduction with mgcv. PeerJ Preprints 6:e27320v1 doi:10.7287/peerj.preprints.27320v1.
Lathrop RC. (2000). Madison Wisconsin Lakes Zooplankton 1976–1994. Environmental Data Initiative.