Title: | Bayesian Super Imposition by Translation and Rotation Growth Curve Analysis |
---|---|
Description: | The Super Imposition by Translation and Rotation (SITAR) model is a shape-invariant nonlinear mixed effect model that fits a natural cubic spline mean curve to the growth data and aligns individual-specific growth curves to the underlying mean curve via a set of random effects (see Cole, 2010 <doi:10.1093/ije/dyq115> for details). The non-Bayesian version of the SITAR model can be fit by using the already available R package 'sitar'. While the 'sitar' package allows modelling of a single outcome only, the 'bsitar' package offers great flexibility in fitting models of varying complexities, including joint modelling of multiple outcomes such as height and weight (multivariate model). Additionally, the 'bsitar' package allows for the simultaneous analysis of an outcome separately for subgroups defined by a factor variable such as gender. This is achieved by fitting separate models for each subgroup (for example males and females for gender variable). An advantage of this approach is that posterior draws for each subgroup are part of a single model object, making it possible to compare coefficients across subgroups and test hypotheses. Since the 'bsitar' package is a front-end to the R package 'brms', it offers excellent support for post-processing of posterior draws via various functions that are directly available from the 'brms' package. In addition, the 'bsitar' package includes various customized functions that allow for the visualization of distance (increase in size with age) and velocity (change in growth rate as a function of age), as well as the estimation of growth spurt parameters such as age at peak growth velocity and peak growth velocity. |
Authors: | Satpal Sandhu [aut, cre, cph] |
Maintainer: | Satpal Sandhu <[email protected]> |
License: | GPL-2 |
Version: | 0.3.2.9000 |
Built: | 2025-02-18 15:32:47 UTC |
Source: | https://github.com/sandhu-ss/bsitar |
The add_model_criterion() function is a wrapper around
brms::add_criterion()
that allows adding fit criteria to a model. Note
that arguments such as compare
and pointwise
are relevant
only for brms::add_loo, while summary
, robust
, and
probs
are ignored except for the brms::bayes_R2()
.
## S3 method for class 'bgmfit' add_model_criterion( model, criterion = c("loo", "waic"), ndraws = NULL, draw_ids = NULL, compare = TRUE, pointwise = FALSE, model_names = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), newdata = NULL, resp = NULL, cores = 1, deriv_model = NULL, verbose = FALSE, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, envir = NULL, ... ) add_model_criterion(model, ...)
## S3 method for class 'bgmfit' add_model_criterion( model, criterion = c("loo", "waic"), ndraws = NULL, draw_ids = NULL, compare = TRUE, pointwise = FALSE, model_names = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), newdata = NULL, resp = NULL, cores = 1, deriv_model = NULL, verbose = FALSE, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, envir = NULL, ... ) add_model_criterion(model, ...)
model |
An object of class |
criterion |
Names of model fit criteria
to compute. Currently supported are |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
compare |
A flag indicating if the information criteria
of the models should be compared to each other
via |
pointwise |
A flag indicating whether to compute the full
log-likelihood matrix at once or separately for each observation.
The latter approach is usually considerably slower but
requires much less working memory. Accordingly, if one runs
into memory issues, |
model_names |
If |
summary |
A logical value indicating whether only the estimate should be
computed ( |
robust |
A logical value to specify the summary options. If |
probs |
The percentiles to be computed by the |
newdata |
An optional data frame for estimation. If |
resp |
A character string (default |
cores |
The number of cores to be used for parallel computations if
|
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
verbose |
A logical argument (default |
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
An object of class bgmfit
with the specified fit criteria added.
Satpal Sandhu [email protected]
brms::add_loo, brms::add_ic()
, brms::add_waic()
,
brms::bayes_R2()
# Fit Bayesian SITAR model # To avoid model estimation which can take time, the Bayesian SITAR model fit # to the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. model <- berkeley_exfit # Add model fit criteria (e.g., WAIC) model <- add_model_criterion(model, criterion = c("waic"))
# Fit Bayesian SITAR model # To avoid model estimation which can take time, the Bayesian SITAR model fit # to the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. model <- berkeley_exfit # Add model fit criteria (e.g., WAIC) model <- add_model_criterion(model, criterion = c("waic"))
Longitudinal growth records for 136 children.
berkeley
berkeley
A data frame with 4884 observations on the following 10 variables:
Factor variable with levels 201-278 for males and 301-385 for females.
Age in years (numeric vector).
Height in cm (numeric vector).
Weight in kg (numeric vector).
Stem length in cm (numeric vector).
Biacromial diameter in cm (numeric vector).
Bi-iliac diameter in cm (numeric vector).
Leg circumference in cm (numeric vector).
Dynamometric
strength in pounds (numeric vector).
Factor variable with level 1 for male and level 2 for female.
The data was originally included as an appendix in the book Physical Growth of California Boys and Girls from Birth to Eighteen Years authored by Tuddenham and Snyder (1954). The dataset was later used as an example in the sitar (Cole 2022) package after correcting transcription errors.
A more detailed description, including the frequency of measurements per year, is provided in the sitar package (Cole 2022). Briefly, the data consists of repeated growth measurements made on 66 boys and 70 girls (ages 0 to 21). The children were born in 1928-29 in Berkeley, California, and were of northern European ancestry. Measurements were taken at the following ages:
0 years (at birth),
0.085 years,
0.25 to 2 years (every 3 months),
2 to 8 years (annually),
8 to 21 years (every 6 months).
The data includes measurements for height, weight (undressed), stem length,
biacromial diameter, bi-iliac diameter, leg circumference, and
dynamometric
strength.
A data frame with 10 columns.
Satpal Sandhu [email protected]
Cole T (2022).
sitar: Super Imposition by Translation and Rotation Growth Curve Analysis.
R package version 1.3.0, https://CRAN.R-project.org/package=sitar.
Tuddenham RD, Snyder MM (1954).
“Physical growth of California boys and girls from birth to eighteen years.”
Publications in Child Development. University of California, Berkeley, 1(2), 183–364.
https://pubmed.ncbi.nlm.nih.gov/13217130/.
A subset of the berkeley data, containing longitudinal growth data for 70 females (aged 8 to 18 years).
berkeley_exdata
berkeley_exdata
A data frame with the following 3 variables:
A factor variable identifying the subject.
Age in years, numeric vector.
Height in centimeters, numeric vector.
Detailed information about the full dataset can be found in the berkeley data.
A data frame with 3 columns.
Satpal Sandhu [email protected]
Bayesian SITAR model fit to the berkeley_exdata dataset (70 females, aged 8 to 18 years).
berkeley_exfit
berkeley_exfit
A model fit object containing a summary of the posterior draws.
Detailed information about the data can be found in the berkeley_exdata dataset.
An object of class bgmfit
containing the posterior draws.
Satpal Sandhu [email protected]
The bsitar() function fits the Bayesian version of the Super Imposition by Translation and Rotation (SITAR) model. The SITAR model is a nonlinear mixed-effects model that has been widely used to summarize growth processes (such as height and weight) from early childhood through adulthood.
The frequentist version of the SITAR model can be fit using the already available R package, sitar (Cole 2022). However, the bsitar package offers an enhanced Bayesian implementation that improves modeling capabilities. In addition to univariate analysis (i.e., modeling a single outcome), bsitar also supports:
Univariate-by-subgroup analysis: This allows for simultaneous modeling of a single outcome across different subgroups defined by a factor variable (e.g., gender). The advantage is that posterior draws for each subgroup are part of a single model object, enabling comparisons of coefficients across groups and testing of various hypotheses.
Multivariate analysis: This approach involves simultaneous joint modeling of two or more outcomes, allowing for more comprehensive growth modeling.
The Bayesian implementation in bsitar provides a more flexible and robust framework for growth curve modeling compared to the frequentist approach.
bsitar( x, y, id, data, df = 4, knots = NA, fixed = a + b + c, random = a + b + c, xoffset = mean, bstart = xoffset, cstart = 0, xfun = NULL, yfun = NULL, bound = 0.04, stype = nsp, terms_rhs = NULL, a_formula = ~1, b_formula = ~1, c_formula = ~1, d_formula = ~1, s_formula = ~1, a_formula_gr = ~1, b_formula_gr = ~1, c_formula_gr = ~1, d_formula_gr = ~1, a_formula_gr_str = NULL, b_formula_gr_str = NULL, c_formula_gr_str = NULL, d_formula_gr_str = NULL, d_adjusted = FALSE, sigma_formula = NULL, sigma_formula_gr = NULL, sigma_formula_gr_str = NULL, sigma_formula_manual = NULL, sigmax = NULL, sigmadf = 4, sigmaknots = NA, sigmafixed = a + b + c, sigmarandom = "", sigmaxoffset = mean, sigmabstart = sigmaxoffset, sigmacstart = 0, sigmaxfun = NULL, sigmabound = 0.04, dpar_formula = NULL, autocor_formula = NULL, family = gaussian(), custom_family = NULL, custom_stanvars = NULL, group_arg = list(groupvar = NULL, by = NULL, cor = un, cov = NULL, dist = gaussian), sigma_group_arg = list(groupvar = NULL, by = NULL, cor = un, cov = NULL, dist = gaussian), univariate_by = list(by = NA, cor = un, terms = subset), multivariate = list(mvar = FALSE, cor = un, rescor = TRUE), a_prior_beta = normal(lm, ysd, autoscale = TRUE), b_prior_beta = normal(0, 1.5, autoscale = FALSE), c_prior_beta = normal(0, 0.5, autoscale = FALSE), d_prior_beta = normal(0, 1, autoscale = TRUE), s_prior_beta = normal(lm, lm, autoscale = TRUE), a_cov_prior_beta = normal(0, 5, autoscale = FALSE), b_cov_prior_beta = normal(0, 1, autoscale = FALSE), c_cov_prior_beta = normal(0, 0.1, autoscale = FALSE), d_cov_prior_beta = normal(0, 1, autoscale = FALSE), s_cov_prior_beta = normal(lm, lm, autoscale = TRUE), a_prior_sd = normal(0, ysd, autoscale = FALSE), b_prior_sd = normal(0, 1, autoscale = FALSE), c_prior_sd = normal(0, 0.25, autoscale = FALSE), d_prior_sd = normal(0, 1, autoscale = TRUE), a_cov_prior_sd = normal(0, 5, autoscale = FALSE), b_cov_prior_sd = normal(0, 1, autoscale = FALSE), c_cov_prior_sd = normal(0, 0.1, autoscale = FALSE), d_cov_prior_sd = normal(0, 1, autoscale = FALSE), a_prior_sd_str = NULL, b_prior_sd_str = NULL, c_prior_sd_str = NULL, d_prior_sd_str = NULL, a_cov_prior_sd_str = NULL, b_cov_prior_sd_str = NULL, c_cov_prior_sd_str = NULL, d_cov_prior_sd_str = NULL, sigma_prior_beta = normal(0, 1, autoscale = FALSE), sigma_cov_prior_beta = normal(0, 0.5, autoscale = FALSE), sigma_prior_sd = normal(0, 0.25, autoscale = FALSE), sigma_cov_prior_sd = normal(0, 0.15, autoscale = FALSE), sigma_prior_sd_str = NULL, sigma_cov_prior_sd_str = NULL, rsd_prior_sigma = normal(0, ysd, autoscale = FALSE), dpar_prior_sigma = normal(0, ysd, autoscale = FALSE), dpar_cov_prior_sigma = normal(0, 1, autoscale = FALSE), autocor_prior_acor = uniform(-1, 1, autoscale = FALSE), autocor_prior_unstr_acor = lkj(1), gr_prior_cor = lkj(1), gr_prior_cor_str = lkj(1), sigma_prior_cor = lkj(1), sigma_prior_cor_str = lkj(1), mvr_prior_rescor = lkj(1), init = NULL, init_r = NULL, a_init_beta = lm, b_init_beta = 0, c_init_beta = 0, d_init_beta = random, s_init_beta = lm, a_cov_init_beta = random, b_cov_init_beta = random, c_cov_init_beta = random, d_cov_init_beta = random, s_cov_init_beta = random, a_init_sd = random, b_init_sd = random, c_init_sd = random, d_init_sd = random, a_cov_init_sd = random, b_cov_init_sd = random, c_cov_init_sd = random, d_cov_init_sd = random, sigma_init_beta = random, sigma_cov_init_beta = random, sigma_init_sd = random, sigma_cov_init_sd = random, gr_init_cor = random, sigma_init_cor = random, rsd_init_sigma = random, dpar_init_sigma = random, dpar_cov_init_sigma = random, autocor_init_acor = random, autocor_init_unstr_acor = random, mvr_init_rescor = random, r_init_z = random, vcov_init_0 = FALSE, jitter_init_beta = NULL, jitter_init_sd = NULL, jitter_init_cor = NULL, prior_data = NULL, init_data = NULL, init_custom = NULL, verbose = FALSE, expose_function = FALSE, get_stancode = FALSE, get_standata = FALSE, get_formula = FALSE, get_stanvars = FALSE, get_priors = FALSE, get_priors_eval = FALSE, get_init_eval = FALSE, validate_priors = FALSE, set_self_priors = NULL, add_self_priors = NULL, set_replace_priors = NULL, set_same_priors_hierarchy = FALSE, outliers = NULL, unused = NULL, chains = 4, iter = 2000, warmup = floor(iter/2), thin = 1, cores = getOption("mc.cores", "optimize"), backend = getOption("brms.backend", "rstan"), threads = getOption("brms.threads", "optimize"), opencl = getOption("brms.opencl", NULL), normalize = getOption("brms.normalize", TRUE), algorithm = getOption("brms.algorithm", "sampling"), control = list(adapt_delta = 0.8, max_treedepth = 15), empty = FALSE, rename = TRUE, pathfinder_args = NULL, pathfinder_init = FALSE, data2 = NULL, data_custom = NULL, sample_prior = "no", save_pars = NULL, drop_unused_levels = TRUE, stan_model_args = list(), refresh = NULL, silent = 1, seed = 123, save_model = NULL, fit = NA, file = NULL, file_compress = TRUE, file_refit = getOption("brms.file_refit", "never"), future = getOption("future", FALSE), parameterization = "ncp", ... )
bsitar( x, y, id, data, df = 4, knots = NA, fixed = a + b + c, random = a + b + c, xoffset = mean, bstart = xoffset, cstart = 0, xfun = NULL, yfun = NULL, bound = 0.04, stype = nsp, terms_rhs = NULL, a_formula = ~1, b_formula = ~1, c_formula = ~1, d_formula = ~1, s_formula = ~1, a_formula_gr = ~1, b_formula_gr = ~1, c_formula_gr = ~1, d_formula_gr = ~1, a_formula_gr_str = NULL, b_formula_gr_str = NULL, c_formula_gr_str = NULL, d_formula_gr_str = NULL, d_adjusted = FALSE, sigma_formula = NULL, sigma_formula_gr = NULL, sigma_formula_gr_str = NULL, sigma_formula_manual = NULL, sigmax = NULL, sigmadf = 4, sigmaknots = NA, sigmafixed = a + b + c, sigmarandom = "", sigmaxoffset = mean, sigmabstart = sigmaxoffset, sigmacstart = 0, sigmaxfun = NULL, sigmabound = 0.04, dpar_formula = NULL, autocor_formula = NULL, family = gaussian(), custom_family = NULL, custom_stanvars = NULL, group_arg = list(groupvar = NULL, by = NULL, cor = un, cov = NULL, dist = gaussian), sigma_group_arg = list(groupvar = NULL, by = NULL, cor = un, cov = NULL, dist = gaussian), univariate_by = list(by = NA, cor = un, terms = subset), multivariate = list(mvar = FALSE, cor = un, rescor = TRUE), a_prior_beta = normal(lm, ysd, autoscale = TRUE), b_prior_beta = normal(0, 1.5, autoscale = FALSE), c_prior_beta = normal(0, 0.5, autoscale = FALSE), d_prior_beta = normal(0, 1, autoscale = TRUE), s_prior_beta = normal(lm, lm, autoscale = TRUE), a_cov_prior_beta = normal(0, 5, autoscale = FALSE), b_cov_prior_beta = normal(0, 1, autoscale = FALSE), c_cov_prior_beta = normal(0, 0.1, autoscale = FALSE), d_cov_prior_beta = normal(0, 1, autoscale = FALSE), s_cov_prior_beta = normal(lm, lm, autoscale = TRUE), a_prior_sd = normal(0, ysd, autoscale = FALSE), b_prior_sd = normal(0, 1, autoscale = FALSE), c_prior_sd = normal(0, 0.25, autoscale = FALSE), d_prior_sd = normal(0, 1, autoscale = TRUE), a_cov_prior_sd = normal(0, 5, autoscale = FALSE), b_cov_prior_sd = normal(0, 1, autoscale = FALSE), c_cov_prior_sd = normal(0, 0.1, autoscale = FALSE), d_cov_prior_sd = normal(0, 1, autoscale = FALSE), a_prior_sd_str = NULL, b_prior_sd_str = NULL, c_prior_sd_str = NULL, d_prior_sd_str = NULL, a_cov_prior_sd_str = NULL, b_cov_prior_sd_str = NULL, c_cov_prior_sd_str = NULL, d_cov_prior_sd_str = NULL, sigma_prior_beta = normal(0, 1, autoscale = FALSE), sigma_cov_prior_beta = normal(0, 0.5, autoscale = FALSE), sigma_prior_sd = normal(0, 0.25, autoscale = FALSE), sigma_cov_prior_sd = normal(0, 0.15, autoscale = FALSE), sigma_prior_sd_str = NULL, sigma_cov_prior_sd_str = NULL, rsd_prior_sigma = normal(0, ysd, autoscale = FALSE), dpar_prior_sigma = normal(0, ysd, autoscale = FALSE), dpar_cov_prior_sigma = normal(0, 1, autoscale = FALSE), autocor_prior_acor = uniform(-1, 1, autoscale = FALSE), autocor_prior_unstr_acor = lkj(1), gr_prior_cor = lkj(1), gr_prior_cor_str = lkj(1), sigma_prior_cor = lkj(1), sigma_prior_cor_str = lkj(1), mvr_prior_rescor = lkj(1), init = NULL, init_r = NULL, a_init_beta = lm, b_init_beta = 0, c_init_beta = 0, d_init_beta = random, s_init_beta = lm, a_cov_init_beta = random, b_cov_init_beta = random, c_cov_init_beta = random, d_cov_init_beta = random, s_cov_init_beta = random, a_init_sd = random, b_init_sd = random, c_init_sd = random, d_init_sd = random, a_cov_init_sd = random, b_cov_init_sd = random, c_cov_init_sd = random, d_cov_init_sd = random, sigma_init_beta = random, sigma_cov_init_beta = random, sigma_init_sd = random, sigma_cov_init_sd = random, gr_init_cor = random, sigma_init_cor = random, rsd_init_sigma = random, dpar_init_sigma = random, dpar_cov_init_sigma = random, autocor_init_acor = random, autocor_init_unstr_acor = random, mvr_init_rescor = random, r_init_z = random, vcov_init_0 = FALSE, jitter_init_beta = NULL, jitter_init_sd = NULL, jitter_init_cor = NULL, prior_data = NULL, init_data = NULL, init_custom = NULL, verbose = FALSE, expose_function = FALSE, get_stancode = FALSE, get_standata = FALSE, get_formula = FALSE, get_stanvars = FALSE, get_priors = FALSE, get_priors_eval = FALSE, get_init_eval = FALSE, validate_priors = FALSE, set_self_priors = NULL, add_self_priors = NULL, set_replace_priors = NULL, set_same_priors_hierarchy = FALSE, outliers = NULL, unused = NULL, chains = 4, iter = 2000, warmup = floor(iter/2), thin = 1, cores = getOption("mc.cores", "optimize"), backend = getOption("brms.backend", "rstan"), threads = getOption("brms.threads", "optimize"), opencl = getOption("brms.opencl", NULL), normalize = getOption("brms.normalize", TRUE), algorithm = getOption("brms.algorithm", "sampling"), control = list(adapt_delta = 0.8, max_treedepth = 15), empty = FALSE, rename = TRUE, pathfinder_args = NULL, pathfinder_init = FALSE, data2 = NULL, data_custom = NULL, sample_prior = "no", save_pars = NULL, drop_unused_levels = TRUE, stan_model_args = list(), refresh = NULL, silent = 1, seed = 123, save_model = NULL, fit = NA, file = NULL, file_compress = TRUE, file_refit = getOption("brms.file_refit", "never"), future = getOption("future", FALSE), parameterization = "ncp", ... )
x |
Predictor variable (typically age in years). For a |
y |
Response variable (e.g., repeated height measurements). For
|
id |
A factor variable uniquely identifying the groups (e.g.,
individuals) in the data frame. For |
data |
A data frame containing variables such as |
df |
Degrees of freedom for the natural cubic spline design matrix
(default |
knots |
A numeric vector specifying the knots for the natural cubic
spline design matrix (default |
fixed |
A character string specifying the fixed effects structure
(default |
random |
A character string specifying the random effects structure
(default |
xoffset |
An optional character string or numeric value to set the
origin of the predictor variable,
For |
bstart |
An optional character string or numeric value to set the origin
of the fixed effect parameter
The default is |
cstart |
An optional character string or numeric value to set the origin
of the fixed effect parameter
Note that since parameter |
xfun |
An optional character string specifying the transformation of the
predictor variable
For |
yfun |
An optional character string specifying the transformation of the
response variable
For |
bound |
An optional real number specifying the value by which the span
of the predictor variable |
stype |
A character string or a named list specifying the spline type to be used. The available options are:
The For more details, see |
terms_rhs |
An optional character string (default For example, when fitting a model with measurement error in the response
variable, the formula in For a Note that |
a_formula |
Formula for the fixed effect parameter, For example, The formula can include a combination of continuous and factor variables, as well as their interactions. |
b_formula |
Formula for the fixed effect parameter, |
c_formula |
Formula for the fixed effect parameter, |
d_formula |
Formula for the fixed effect parameter, |
s_formula |
Formula for the fixed effect parameter, |
a_formula_gr |
Formula for the random effect parameter,
To specify the group identifier (e.g.,
Here, An alternative approach to specify the group identifier and correlation
structure is through the
and use |
b_formula_gr |
Formula for the random effect parameter, |
c_formula_gr |
Formula for the random effect parameter, |
d_formula_gr |
Formula for the random effect parameter, |
a_formula_gr_str |
Formula for the random effect parameter, For In this example, Additionally, users can specify models with any number of hierarchical levels and include covariates in the random effect formula. |
b_formula_gr_str |
Formula for the random effect parameter, |
c_formula_gr_str |
Formula for the random effect parameter, |
d_formula_gr_str |
Formula for the random effect parameter, |
d_adjusted |
A logical indicator to adjust the scale of the predictor
variable |
sigma_formula |
Formula for the fixed effect distributional parameter,
It is important to note that an alternative way to set up the fixed effect
design matrix for the distributional parameter
Users can specify an external function, such as |
sigma_formula_gr |
Formula for the random effect parameter, |
sigma_formula_gr_str |
Formula for the random effect parameter,
|
sigma_formula_manual |
Formula for the random effect parameter,
Another use case for
Here, Note that for |
sigmax |
Predictor for the distributional parameter |
sigmadf |
Degree of freedom for the spline function used for
|
sigmaknots |
Knots for the spline function used for |
sigmafixed |
Fixed effect formula for the |
sigmarandom |
Random effect formula for the |
sigmaxoffset |
Offset for the |
sigmabstart |
Starting value for the |
sigmacstart |
Starting value for the |
sigmaxfun |
Transformation function for |
sigmabound |
Bounds for the |
dpar_formula |
Formula for the distributional fixed effect parameter,
|
autocor_formula |
Formula to set up the autocorrelation structure of
residuals (default
See |
family |
Family distribution (default |
custom_family |
Specifies custom families (i.e., response distribution).
Default is |
custom_stanvars |
Allows the preparation and passing of user-defined
variables to be added to Stan's program blocks (default |
group_arg |
Specify arguments for group-level random effects. The
Note that it is not necessary to define all or any of these options
( |
sigma_group_arg |
Specify arguments for modeling distributional-level
random effects for |
univariate_by |
Set up the univariate-by-subgroup model fitting (default
|
multivariate |
Set up the multivariate model fitting (default
|
a_prior_beta |
Specify priors for the fixed effect parameter,
|
b_prior_beta |
Specify priors for the fixed effect parameter,
|
c_prior_beta |
Specify priors for the fixed effect parameter,
|
d_prior_beta |
Specify priors for the fixed effect parameter,
|
s_prior_beta |
Specify priors for the fixed effect parameter,
It is observed that location-scale based prior distributions (such as
|
a_cov_prior_beta |
Specify priors for the covariate(s) included in the
fixed effect parameter,
|
b_cov_prior_beta |
Specify priors for the covariate(s) included in the
fixed effect parameter, |
c_cov_prior_beta |
Specify priors for the covariate(s) included in the
fixed effect parameter, |
d_cov_prior_beta |
Specify priors for the covariate(s) included in the
fixed effect parameter, |
s_cov_prior_beta |
Specify priors for the covariate(s) included in the
fixed effect parameter, |
a_prior_sd |
Specify priors for the random effect parameter, |
b_prior_sd |
Specify priors for the random effect parameter, |
c_prior_sd |
Specify priors for the random effect parameter, |
d_prior_sd |
Specify priors for the random effect parameter, |
a_cov_prior_sd |
Specify priors for the covariate(s) included in the
random effect parameter, |
b_cov_prior_sd |
Specify priors for the covariate(s) included in the
random effect parameter, |
c_cov_prior_sd |
Specify priors for the covariate(s) included in the
random effect parameter, |
d_cov_prior_sd |
Specify priors for the covariate(s) included in the
random effect parameter, |
a_prior_sd_str |
Specify priors for the random effect parameter,
|
b_prior_sd_str |
Specify priors for the random effect parameter,
|
c_prior_sd_str |
Specify priors for the random effect parameter,
|
d_prior_sd_str |
Specify priors for the random effect parameter,
|
a_cov_prior_sd_str |
Specify priors for the covariate(s) included in the
random effect parameter, |
b_cov_prior_sd_str |
Specify priors for the covariate(s) included in the
random effect parameter, |
c_cov_prior_sd_str |
Specify priors for the covariate(s) included in the
random effect parameter, |
d_cov_prior_sd_str |
Specify priors for the covariate(s) included in the
random effect parameter, |
sigma_prior_beta |
Specify priors for the fixed effect distributional
parameter, |
sigma_cov_prior_beta |
Specify priors for the covariate(s) included in
the fixed effect distributional parameter, |
sigma_prior_sd |
Specify priors for the random effect distributional
parameter, |
sigma_cov_prior_sd |
Specify priors for the covariate(s) included in the
random effect distributional parameter, |
sigma_prior_sd_str |
Specify priors for the random effect distributional
parameter, |
sigma_cov_prior_sd_str |
Specify priors for the covariate(s) included in
the random effect distributional parameter, |
rsd_prior_sigma |
Specify priors for the residual standard deviation
parameter |
dpar_prior_sigma |
Specify priors for the fixed effect distributional
parameter |
dpar_cov_prior_sigma |
Specify priors for the covariate(s) included in
the fixed effect distributional parameter |
autocor_prior_acor |
Specify priors for the autocorrelation parameters
when fitting a model with |
autocor_prior_unstr_acor |
Specify priors for the autocorrelation
parameters when fitting a model with the unstructured ( |
gr_prior_cor |
Specify priors for the correlation parameter(s) of
group-level random effects (default |
gr_prior_cor_str |
Specify priors for the correlation parameter(s) of
group-level random effects when fitting a hierarchical model with three or
more levels of hierarchy (default |
sigma_prior_cor |
Specify priors for the correlation parameter(s) of
distributional random effects |
sigma_prior_cor_str |
Specify priors for the correlation parameter(s) of
distributional random effects |
mvr_prior_rescor |
Specify priors for the residual correlation parameter
when fitting a multivariate model (default |
init |
Initial values for the sampler. Options include:
|
init_r |
A positive real value that defines the range for the random
generation of initial values (default |
a_init_beta |
Initial values for the fixed effect parameter,
Note that options |
b_init_beta |
Initial values for the fixed effect parameter, |
c_init_beta |
Initial values for the fixed effect parameter, |
d_init_beta |
Initial values for the fixed effect parameter, |
s_init_beta |
Initial values for the fixed effect parameter,
|
a_cov_init_beta |
Initial values for the covariate(s) included in the
fixed effect parameter,
Note that the |
b_cov_init_beta |
Initial values for the covariate(s) included in the
fixed effect parameter, |
c_cov_init_beta |
Initial values for the covariate(s) included in the
fixed effect parameter, |
d_cov_init_beta |
Initial values for the covariate(s) included in the
fixed effect parameter, |
s_cov_init_beta |
Initial values for the covariate(s) included in the
fixed effect parameter, |
a_init_sd |
Initial value for the standard deviation of the group-level
random effect parameter,
Note that the options Additionally, when fitting |
b_init_sd |
Initial value for the standard deviation of the group-level
random effect parameter, |
c_init_sd |
Initial value for the standard deviation of the group-level
random effect parameter, |
d_init_sd |
Initial value for the standard deviation of the group-level
random effect parameter, |
a_cov_init_sd |
Initial values for the covariate(s) included in the
random effect parameter
|
b_cov_init_sd |
Initial values for the covariate(s) included in the
random effect parameter |
c_cov_init_sd |
Initial values for the covariate(s) included in the
random effect parameter |
d_cov_init_sd |
Initial values for the covariate(s) included in the
random effect parameter |
sigma_init_beta |
Initial values for the fixed effect distributional
parameter
|
sigma_cov_init_beta |
Initial values for the covariate(s) included in
the fixed effect distributional parameter |
sigma_init_sd |
Initial value for the standard deviation of the
distributional random effect parameter |
sigma_cov_init_sd |
Initial values for the covariate(s) included in the
distributional random effect parameter |
gr_init_cor |
Initial values for the correlation parameters of
group-level random effects parameters (default
|
sigma_init_cor |
Initial values for the correlation parameters of
distributional random effects parameter
|
rsd_init_sigma |
Initial values for the residual standard deviation
parameter,
Note that if |
dpar_init_sigma |
Initial values for the distributional parameter
|
dpar_cov_init_sigma |
Initial values for the covariate(s) included in
the distributional parameter |
autocor_init_acor |
Initial values for the autocorrelation parameter
(see |
autocor_init_unstr_acor |
Initial values for unstructured residual
autocorrelation parameters (default |
mvr_init_rescor |
Initial values for the residual correlation parameter
when fitting a |
r_init_z |
Initial values for the standardized group-level random effect
parameters (default |
vcov_init_0 |
A logical (default |
jitter_init_beta |
A proportion (between 0 and 1) to perturb the initial
values for fixed effect parameters. The default is |
jitter_init_sd |
A proportion (between 0 and 1) to perturb the initial
values for the standard deviation of random effect parameters. The default
is |
jitter_init_cor |
A proportion (between 0 and 1) to perturb the initial
values for the correlation parameters of random effects. The default is
|
prior_data |
An optional argument (a named list, default
|
init_data |
An optional argument (a named list, default |
init_custom |
Specify a custom initialization object (a named list). The
named list is directly passed to the |
verbose |
An optional argument (logical, default |
expose_function |
An optional argument (logical, default |
get_stancode |
An optional argument (logical, default |
get_standata |
An optional argument (logical, default |
get_formula |
An optional argument (logical, default |
get_stanvars |
An optional argument (logical, default |
get_priors |
An optional argument (logical, default |
get_priors_eval |
An optional argument (logical, default |
get_init_eval |
An optional argument (logical, default |
validate_priors |
An optional argument (logical, default |
set_self_priors |
An optional argument (default |
add_self_priors |
An optional argument (default |
set_replace_priors |
An optional argument (default |
set_same_priors_hierarchy |
An optional argument (default |
outliers |
An optional argument (default |
unused |
An optional formula defining variables that are unused in the model but should still be stored in the model's data frame. Useful when variables are needed during post-processing. |
chains |
The number of Markov chains (default 4). |
iter |
The total number of iterations per chain, including warmup (default 2000). |
warmup |
A positive integer specifying the number of warmup (aka
burn-in) iterations. This also specifies the number of iterations used for
stepsize adaptation, so warmup draws should not be used for inference. The
number of warmup iterations should not exceed |
thin |
A positive integer specifying the thinning interval. Set
|
cores |
Number of cores to be used when executing the chains in
parallel. See Another option is to set These options can be set globally using |
backend |
A character string specifying the package to be used when
executing the Stan model. The available options are |
threads |
Number of threads to be used in within-chain parallelization.
Note that unlike the |
opencl |
The platform and device IDs of the OpenCL device to use for GPU
support during model fitting. If you are unsure about the IDs of your
OpenCL device, |
normalize |
Logical flag indicating whether normalization constants
should be included in the Stan code (default is |
algorithm |
A character string specifying the estimation method to use. Available options are:
This parameter can be set globally via the |
control |
A named |
empty |
Logical. If |
rename |
For internal use only. |
pathfinder_args |
A named |
pathfinder_init |
A logical value (default |
data2 |
A named |
data_custom |
A |
sample_prior |
A character string indicating whether to draw samples
from the priors in addition to the posterior draws. Options are |
save_pars |
An object generated by |
drop_unused_levels |
A logical value indicating whether unused factor
levels in the data should be dropped. The default is |
stan_model_args |
A |
refresh |
An integer specifying the frequency of printing every nth
iteration. By default, |
silent |
A verbosity level between |
seed |
An integer or |
save_model |
A character string or |
fit |
An instance of class |
file |
Either |
file_compress |
Logical or a character string, specifying one of the
compression algorithms supported by |
file_refit |
Modifies when the fit stored via the
If you believe a false positive occurred, you can use
|
future |
Logical; If |
parameterization |
A character string specifying the type of
parameterization to use for drawing group-level random effects. Options
are: The NCP is generally recommended when the likelihood is weak (e.g., few
observations per individual) and is the default approach (and only option)
in The CP parameterization is typically more efficient when a relatively large
number of observations are available across individuals. We consider a
'relatively large number' as at least 10 repeated measurements per
individual. If there are fewer than 10, NCP is used automatically. This
behavior applies only when Note that since |
... |
Further arguments passed to These internal arguments are typically not used in regular model fitting but can be relevant for certain testing scenarios or advanced customization. Users are generally not expected to interact with these unless working on debugging or testing specific features of the model fitting process. |
The SITAR is a shape-invariant nonlinear mixed-effects growth
curve model that fits a population average (i.e., mean) curve to the data and
aligns each individual's growth trajectory to the underlying population curve
via a set of (typically) three random effects: size
, timing
,
and intensity
. Additionally, a slope parameter can be included as a
random effect to estimate the variability in adult growth rate (see
sitar::sitar()
for details).
The concept of a shape-invariant model (SIM) was first introduced by Lindstrom (1995), and later used by Beath (2007) to model infant growth data (birth to 2 years). The current version of the SITAR model was developed by Cole et al. (2010) and has been extensively used for modeling growth data (see Nembidzane et al. 2020 and Sandhu 2020).
The frequentist version of the SITAR model can be fit using the
already available R package, sitar (Cole 2022). The
framework of the Bayesian implementation of the SITAR model in the
bsitar package is similar to the sitar package, with the main
difference being that sitar uses splines::ns()
to construct the
B-splines based natural cubic spline design matrix, whereas bsitar
implements a different strategy to create natural cubic splines. The
bsitar offers three different types of splines: nsp, nsk,
and rcs. Both nsp and nsk use the B-splines basis to
generate the natural cubic spline design matrix as implemented in
splines2::nsp()
and splines2::nsk()
, whereas rcs is based on the
truncated power basis approach (see
Harrell and others (2001) and
Harrell Jr. (2022) for details) to construct the spline
design matrix. While all approaches produce the same growth curves, the
model-estimated spline coefficients differ from each other.
Like the sitar package (Cole et al. 2010), the bsitar
package fits the SITAR model with (usually) three random effects: size
(parameter a
), timing (parameter b
), and intensity (parameter
c
). Additionally, there is a slope parameter (parameter d
) that
models the variability in the adult slope of the growth curve (see
sitar::sitar()
for details).
Note that the author of the sitar package (Cole et al. 2010)
enforces the inclusion of the d
parameter as a random effect only,
excluding it from the fixed structure of the model. However, the bsitar
package allows inclusion of the d
parameter in both the fixed and/or
random effects structures of the SITAR model.
For the three-parameter version of the SITAR model (default), the
fixed effects structure (i.e., population average trajectory) is specified as
fixed = 'a+b+c'
, and the random effects structure, capturing the
deviation of individual trajectories from the population average curve, is
specified as random = 'a+b+c'
.
The bsitar package offers flexibility in model specification. For example:
A fixed-effect version of the SITAR model can be fit by
setting random = ''
.
The fixed-effect structure can include a
subset of parameters,
such as size and timing (fixed = 'a+b'
) or size and intensity
(fixed = 'a+c'
).
For a four-parameter version of the SITAR model, parameter
d
is included in the fixed
and/or random
arguments.
The sitar package internally depends on the brms package (see Bürkner 2022; Bürkner 2021), which fits a wide range of hierarchical linear and nonlinear regression models, including multivariate models. The brms package itself depends on Stan for full Bayesian inference (see Stan Development Team 2023; Gelman et al. 2015). Like brms, the bsitar package allows flexible prior specifications based on user's knowledge of growth processes (e.g., timing and intensity of growth spurts).
The brms package uses a combination of normal
and
student_t
distributions for regression coefficients, group-level
random effects, and the distributional parameter (sigma
), while
rstanarm uses normal
distributions for regression coefficients
and group-level random effects, but sets exponential
for the
distributional parameter (sigma
). By default, bsitar uses
normal
distributions for all parameters, including regression
coefficients, standard deviations of group-level random effects, and the
distributional parameter. Additionally, bsitar provides flexibility in
choosing scale parameters for location-scale distributions (such as
normal
and student_t
).
The bsitar package also allows three types of model specifications:
'univariate'
, 'univariate_by'
, and 'multivariate'
:
'univariate'
fits a single model to an outcome variable.
'univariate_by'
fits two or more sub-models to an outcome
defined by a factor variable (e.g., sex).
'multivariate'
fits a joint model to multiple outcomes with
shared random effects.
The bsitar package offers full flexibility in specifying predictors,
degrees of freedom for design matrices, priors, and initial values. The
package also allows users to specify options in a user-friendly manner (e.g.,
univariate_by = sex
is equivalent to univariate_by = 'sex'
).
An object of class brmsfit, bsitar
, which contains the
posterior draws, model coefficients, and other useful information related
to the model fitting. This object includes details such as the fitted
model, the data used, prior distributions, and any other relevant outputs
from the Stan model fitting process. The resulting object can be used for
further analysis, diagnostics, and post-processing, including model summary
statistics, predictions, and visualizations.
The package is under continuous development, and new models, post-processing features, and improvements are being actively worked on. Keep an eye on future releases for additional functionality and updates to enhance model fitting, diagnostics, and analysis capabilities.
Satpal Sandhu [email protected]
Beath KJ (2007).
“Infant growth modelling using a shape invariant model with random effects.”
Statistics in Medicine, 26(12), 2547–2564.
doi:10.1002/sim.2718, Type: Journal article.
Bürkner P (2021).
“Bayesian Item Response Modeling in R with brms and Stan.”
Journal of Statistical Software, 100(5), 1–54.
doi:10.18637/jss.v100.i05.
Bürkner P (2022).
brms: Bayesian Regression Models using Stan.
R package version 2.18.0, https://CRAN.R-project.org/package=brms.
Cole T (2022).
sitar: Super Imposition by Translation and Rotation Growth Curve Analysis.
R package version 1.3.0, https://CRAN.R-project.org/package=sitar.
Cole TJ, Donaldson MDC, Ben-Shlomo Y (2010).
“SITAR—a useful instrument for growth curve analysis.”
International Journal of Epidemiology, 39(6), 1558–1566.
ISSN 0300-5771, doi:10.1093/ije/dyq115, tex.eprint: https://academic.oup.com/ije/article-pdf/39/6/1558/18480886/dyq115.pdf.
Gelman A, Lee D, Guo J (2015).
“Stan: A Probabilistic Programming Language for Bayesian Inference and Optimization.”
Journal of Educational and Behavioral Statistics, 40(5), 530-543.
doi:10.3102/1076998615606113.
Harrell FE, others (2001).
Regression modeling strategies: with applications to linear models, logistic regression, and survival analysis, volume 608.
Springer.
Harrell Jr. FE (2022).
Hmisc: Harrell Miscellaneous.
R package version 4.7-2, https://hbiostat.org/R/Hmisc/.
Lindstrom MJ (1995).
“Self-modelling with random shift and scale parameters and a free-knot spline shape function.”
Statistics in Medicine, 14(18), 2009-2021.
doi:10.1002/sim.4780141807, https://pubmed.ncbi.nlm.nih.gov/8677401/.
Nembidzane C, Lesaoana M, Monyeki KD, Boateng A, Makgae PJ (2020).
“Using the SITAR Method to Estimate Age at Peak Height Velocity of Children in Rural South Africa: Ellisras Longitudinal Study.”
Children, 7(3), 17.
ISSN 2227-9067, doi:10.3390/children7030017, https://www.mdpi.com/2227-9067/7/3/17.
Sandhu SS (2020).
Analysis of longitudinal jaw growth data to study sex differences in timing and intensity of the adolescent growth spurt for normal growth and skeletal discrepancies.
Thesis, University of Bristol.
Stan Development Team (2023).
Stan Reference Manual version 2.31.
https://mc-stan.org/docs/reference-manual/.
brms::brm()
brms::brmsformula()
brms::prior()
# Below, we fit a SITAR model to a subset of the Berkley height data, # specifically the data for 70 girls between the ages of 8 and 18. # This subset is used as an example in the vignette for the 'sitar' package. # # The original Berkley height data contains repeated growth measurements for # 66 boys and 70 girls (ages 0-21). For this example, we use a subset of the # data for 70 girls aged 8 to 18 years. # # For details on the full Berkley height dataset, refer to 'sitar' package # documentation (help file: ?sitar::berkeley). Further details on the subset # of the data used here can be found in the vignette ('Fitting_models_with_SITAR', # package = 'sitar'). # Load the 'berkeley_exdata' that has been pre-saved berkeley_exdata <- getNsObject(berkeley_exdata) # Fit frequentist SITAR model with df = 3 using the sitar package model_ml <- sitar::sitar(x = age, y = height, id = id, df = 3, data = berkeley_exdata, xoffset = 'mean', fixed = 'a+b+c', random = 'a+b+c', a.formula = ~1, b.formula = ~1, c.formula = ~1 ) # Fit Bayesian SITAR model # To avoid time-consuming model estimation, the Bayesian SITAR model fit has # been saved as an example fit ('berkeley_exfit'). This model was fit using # 2 chains (2000 iterations per chain) with thinning set to 5 for memory # efficiency. Users are encouraged to refit the model using default settings # (4 chains, 2000 iterations per chain, thin = 1) as suggested by the Stan team. # Note that with thinning set to 5 (thin = 5), only one fifth of total draws # will be saved and hence the effective sample size is expected to be small. # Check if the pre-saved model 'berkeley_exfit' exists # berkeley_exfit <- bsitar:::berkeley_exfit berkeley_exfit <- getNsObject(berkeley_exfit) if(exists('berkeley_exfit')) { model <- berkeley_exfit } else { # Fit model with default priors # Refer to the documentation for prior on each parameter model <- bsitar(x = age, y = height, id = id, df = 3, data = berkeley_exdata, xoffset = 'mean', fixed = 'a+b+c', random = 'a+b+c', a_formula = ~1, b_formula = ~1, c_formula = ~1, threads = brms::threading(NULL), chains = 2, cores = 2, iter = 2000, thin = 5) } # Generate model summary summary(model) # Compare model summary with the frequentist SITAR model print(model_ml) # Check model fit via posterior predictive checks using plot_ppc. # This function is based on pp_check from the 'brms' package. plot_ppc(model, ndraws = 100) # Plot distance and velocity curves using plot_conditional_effects. # This function works like conditional_effects from the 'brms' package, # with the added option to plot velocity curves. # Distance curve plot_conditional_effects(model, deriv = 0) # Velocity curve plot_conditional_effects(model, deriv = 1) # Plot distance and velocity curves along with parameter estimates using # plot_curves (similar to plot.sitar from the sitar package). plot_curves(model, apv = TRUE) # Compare plots with the frequentist SITAR model plot(model_ml)
# Below, we fit a SITAR model to a subset of the Berkley height data, # specifically the data for 70 girls between the ages of 8 and 18. # This subset is used as an example in the vignette for the 'sitar' package. # # The original Berkley height data contains repeated growth measurements for # 66 boys and 70 girls (ages 0-21). For this example, we use a subset of the # data for 70 girls aged 8 to 18 years. # # For details on the full Berkley height dataset, refer to 'sitar' package # documentation (help file: ?sitar::berkeley). Further details on the subset # of the data used here can be found in the vignette ('Fitting_models_with_SITAR', # package = 'sitar'). # Load the 'berkeley_exdata' that has been pre-saved berkeley_exdata <- getNsObject(berkeley_exdata) # Fit frequentist SITAR model with df = 3 using the sitar package model_ml <- sitar::sitar(x = age, y = height, id = id, df = 3, data = berkeley_exdata, xoffset = 'mean', fixed = 'a+b+c', random = 'a+b+c', a.formula = ~1, b.formula = ~1, c.formula = ~1 ) # Fit Bayesian SITAR model # To avoid time-consuming model estimation, the Bayesian SITAR model fit has # been saved as an example fit ('berkeley_exfit'). This model was fit using # 2 chains (2000 iterations per chain) with thinning set to 5 for memory # efficiency. Users are encouraged to refit the model using default settings # (4 chains, 2000 iterations per chain, thin = 1) as suggested by the Stan team. # Note that with thinning set to 5 (thin = 5), only one fifth of total draws # will be saved and hence the effective sample size is expected to be small. # Check if the pre-saved model 'berkeley_exfit' exists # berkeley_exfit <- bsitar:::berkeley_exfit berkeley_exfit <- getNsObject(berkeley_exfit) if(exists('berkeley_exfit')) { model <- berkeley_exfit } else { # Fit model with default priors # Refer to the documentation for prior on each parameter model <- bsitar(x = age, y = height, id = id, df = 3, data = berkeley_exdata, xoffset = 'mean', fixed = 'a+b+c', random = 'a+b+c', a_formula = ~1, b_formula = ~1, c_formula = ~1, threads = brms::threading(NULL), chains = 2, cores = 2, iter = 2000, thin = 5) } # Generate model summary summary(model) # Compare model summary with the frequentist SITAR model print(model_ml) # Check model fit via posterior predictive checks using plot_ppc. # This function is based on pp_check from the 'brms' package. plot_ppc(model, ndraws = 100) # Plot distance and velocity curves using plot_conditional_effects. # This function works like conditional_effects from the 'brms' package, # with the added option to plot velocity curves. # Distance curve plot_conditional_effects(model, deriv = 0) # Velocity curve plot_conditional_effects(model, deriv = 1) # Plot distance and velocity curves along with parameter estimates using # plot_curves (similar to plot.sitar from the sitar package). plot_curves(model, apv = TRUE) # Compare plots with the frequentist SITAR model plot(model_ml)
The expose_model_functions() function is a wrapper
around rstan::expose_stan_functions()
that exposes user-defined Stan
function(s). These functions are necessary for post-processing the
posterior draws.
## S3 method for class 'bgmfit' expose_model_functions( model, scode = NULL, expose = TRUE, select_model = NULL, returnobj = TRUE, vectorize = FALSE, verbose = FALSE, envir = NULL, ... ) expose_model_functions(model, ...)
## S3 method for class 'bgmfit' expose_model_functions( model, scode = NULL, expose = TRUE, select_model = NULL, returnobj = TRUE, vectorize = FALSE, verbose = FALSE, envir = NULL, ... ) expose_model_functions(model, ...)
model |
An object of class |
scode |
A character string containing the user-defined Stan function(s)
in |
expose |
A logical (default |
select_model |
A character string (default |
returnobj |
A logical (default |
vectorize |
A logical (default |
verbose |
A logical argument (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the
|
An object of class bgmfit
if returnobj = TRUE
;
otherwise, it returns NULL
invisibly.
Satpal Sandhu [email protected]
rstan::expose_stan_functions()
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # To save time, argument expose is set as FALSE, which runs a dummy test # and avoids model compilation that often takes time. expose_model_functions(model, expose = FALSE)
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # To save time, argument expose is set as FALSE, which runs a dummy test # and avoids model compilation that often takes time. expose_model_functions(model, expose = FALSE)
The fitted_draws() function is a wrapper around the
brms::fitted.brmsfit()
function, which allows users to obtain fitted
values (and their summaries) from the posterior draws. For more details,
refer to the documentation for brms::fitted.brmsfit()
.
## S3 method for class 'bgmfit' fitted_draws( model, newdata = NULL, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "uncertainty", incl_autocor = TRUE, numeric_cov_at = NULL, levels_id = NULL, avg_reffects = NULL, aux_variables = NULL, ipts = 10, deriv = 0, deriv_model = TRUE, summary = TRUE, robust = FALSE, transform = NULL, probs = c(0.025, 0.975), xrange = NULL, xrange_search = NULL, parms_eval = FALSE, parms_method = "getPeak", idata_method = NULL, verbose = FALSE, fullframe = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) fitted_draws(model, ...)
## S3 method for class 'bgmfit' fitted_draws( model, newdata = NULL, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "uncertainty", incl_autocor = TRUE, numeric_cov_at = NULL, levels_id = NULL, avg_reffects = NULL, aux_variables = NULL, ipts = 10, deriv = 0, deriv_model = TRUE, summary = TRUE, robust = FALSE, transform = NULL, probs = c(0.025, 0.975), xrange = NULL, xrange_search = NULL, parms_eval = FALSE, parms_method = "getPeak", idata_method = NULL, verbose = FALSE, fullframe = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) fitted_draws(model, ...)
model |
An object of class |
newdata |
An optional data frame for estimation. If |
resp |
A character string (default |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
re_formula |
Option to indicate whether or not to include
individual/group-level effects in the estimation. When |
allow_new_levels |
A flag indicating if new levels of group-level
effects are allowed (defaults to |
sample_new_levels |
Indicates how to sample new levels for grouping
factors specified in |
incl_autocor |
A flag indicating if correlation structures originally
specified via |
numeric_cov_at |
An optional (named list) argument to specify the value
of continuous covariate(s). The default |
levels_id |
An optional argument to specify the |
avg_reffects |
An optional argument (default |
aux_variables |
An optional argument to specify the variable(s) that can
be passed to the |
ipts |
An integer to set the length of the predictor variable for
generating a smooth velocity curve. If |
deriv |
An integer indicating whether to estimate the distance curve
or its derivative (velocity curve). The default |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
summary |
A logical value indicating whether only the estimate should be
computed ( |
robust |
A logical value to specify the summary options. If |
transform |
A function applied to individual draws from the posterior
distribution before computing summaries. The argument |
probs |
The percentiles to be computed by the |
xrange |
An integer to set the predictor range (e.g., age) when
executing the interpolation via |
xrange_search |
A vector of length two or a character string
|
parms_eval |
A logical value to specify whether or not to compute growth parameters on the fly. This is for internal use only and is mainly needed for compatibility across internal functions. |
parms_method |
A character string specifying the method used when
evaluating |
idata_method |
A character string to indicate the interpolation method.
The number of interpolation points is set by the
|
verbose |
A logical argument (default |
fullframe |
A logical value indicating whether to return a
|
dummy_to_factor |
A named list (default
|
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
funlist |
A list (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The fitted_draws() function computes the fitted values
from the posterior draws. While the brms::fitted.brmsfit()
function
from the brms package can be used to obtain fitted (distance)
values when the outcome (e.g., height) is untransformed, it returns
fitted values on the log or square root scale if the outcome is
transformed. In contrast, fitted_draws() returns fitted values
on the original scale. Additionally, fitted_draws() computes
the first derivative (velocity) on the original scale, after applying
the necessary back-transformation. Apart from these differences, both
functions—brms::fitted.brmsfit()
and fitted_draws()
—operate in the
same manner, allowing users to specify all options available in
brms::fitted.brmsfit()
.
An array of predicted mean response values when summarise =
FALSE
, or a data.frame
when summarise = TRUE
. For further
details, refer to brms::fitted.brmsfit.
Satpal Sandhu [email protected]
# Fit Bayesian SITAR model # To avoid time-consuming model estimation, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See the 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check if the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance curve fitted_draws(model, deriv = 0, re_formula = NA) # Individual-specific distance curves fitted_draws(model, deriv = 0, re_formula = NULL) # Population average velocity curve fitted_draws(model, deriv = 1, re_formula = NA) # Individual-specific velocity curves fitted_draws(model, deriv = 1, re_formula = NULL)
# Fit Bayesian SITAR model # To avoid time-consuming model estimation, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See the 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check if the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance curve fitted_draws(model, deriv = 0, re_formula = NA) # Individual-specific distance curves fitted_draws(model, deriv = 0, re_formula = NULL) # Population average velocity curve fitted_draws(model, deriv = 1, re_formula = NA) # Individual-specific velocity curves fitted_draws(model, deriv = 1, re_formula = NULL)
This function checks if an object exists within a specified namespace and returns the object if it exists. The object must be provided as a symbol (not a character string). The function is designed to facilitate the retrieval of model or other objects from a specified environment or namespace. This function is mainly for internal purposes.
getNsObject(object, namespace = NULL, envir = NULL)
getNsObject(object, namespace = NULL, envir = NULL)
object |
A symbol representing the object to be retrieved. The input must be a symbol (i.e., not a character string) corresponding to an existing object within the specified namespace. |
namespace |
A character string specifying the namespace to check for the object. If the object exists within the given namespace, it will be returned. |
envir |
An environment in which to search for the object. If set to
|
The object of the same class as the input object
, if it
exists. If the object doesn't exist in the specified namespace or
environment, an error is raised.
Satpal Sandhu [email protected]
# Check whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit)
# Check whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit)
The growthparameters_comparison() function estimates
and compares growth parameters, such as peak growth velocity and the age at
peak growth velocity. This function serves as a wrapper around
marginaleffects::comparisons()
and marginaleffects::avg_comparisons()
.
The marginaleffects::comparisons()
function computes unit-level
(conditional) estimates, whereas marginaleffects::avg_comparisons()
returns average (marginal) estimates. A detailed explanation is available
here. Note that for the current use case—
estimating and comparing growth parameters—the arguments variables
and
comparison
in marginaleffects::comparisons()
and
marginaleffects::avg_comparisons()
are modified (see below).
Furthermore, comparisons of growth parameters are performed via the
hypothesis
argument of both the marginaleffects::comparisons()
and
marginaleffects::avg_comparisons()
functions. Please note that the
marginaleffects package is highly flexible, and users are expected to
have a strong understanding of its workings. Additionally, since the
marginaleffects package is rapidly evolving, results obtained from the
current implementation should be considered experimental.
## S3 method for class 'bgmfit' growthparameters_comparison( model, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, newdata = NULL, datagrid = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "gaussian", parameter = NULL, xrange = 1, acg_velocity = 0.1, digits = 2, numeric_cov_at = NULL, aux_variables = NULL, levels_id = NULL, avg_reffects = NULL, idata_method = NULL, ipts = NULL, seed = 123, future = FALSE, future_session = "multisession", future_splits = NULL, future_method = "future", future_re_expose = NULL, usedtplyr = FALSE, usecollapse = TRUE, parallel = FALSE, cores = NULL, average = FALSE, plot = FALSE, showlegends = NULL, variables = NULL, deriv = NULL, deriv_model = NULL, method = "custom", marginals = NULL, pdraws = FALSE, pdrawso = FALSE, pdrawsp = FALSE, pdrawsh = FALSE, comparison = "difference", type = NULL, by = FALSE, bys = NULL, conf_level = 0.95, transform = NULL, cross = FALSE, wts = NULL, hypothesis = NULL, equivalence = NULL, eps = NULL, constrats_by = FALSE, constrats_at = FALSE, constrats_subset = FALSE, reformat = NULL, estimate_center = NULL, estimate_interval = NULL, dummy_to_factor = NULL, verbose = FALSE, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) growthparameters_comparison(model, ...)
## S3 method for class 'bgmfit' growthparameters_comparison( model, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, newdata = NULL, datagrid = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "gaussian", parameter = NULL, xrange = 1, acg_velocity = 0.1, digits = 2, numeric_cov_at = NULL, aux_variables = NULL, levels_id = NULL, avg_reffects = NULL, idata_method = NULL, ipts = NULL, seed = 123, future = FALSE, future_session = "multisession", future_splits = NULL, future_method = "future", future_re_expose = NULL, usedtplyr = FALSE, usecollapse = TRUE, parallel = FALSE, cores = NULL, average = FALSE, plot = FALSE, showlegends = NULL, variables = NULL, deriv = NULL, deriv_model = NULL, method = "custom", marginals = NULL, pdraws = FALSE, pdrawso = FALSE, pdrawsp = FALSE, pdrawsh = FALSE, comparison = "difference", type = NULL, by = FALSE, bys = NULL, conf_level = 0.95, transform = NULL, cross = FALSE, wts = NULL, hypothesis = NULL, equivalence = NULL, eps = NULL, constrats_by = FALSE, constrats_at = FALSE, constrats_subset = FALSE, reformat = NULL, estimate_center = NULL, estimate_interval = NULL, dummy_to_factor = NULL, verbose = FALSE, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) growthparameters_comparison(model, ...)
model |
An object of class |
resp |
A character string (default |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
newdata |
An optional data frame for estimation. If |
datagrid |
A grid of user-specified values to be used in the
|
re_formula |
Option to indicate whether or not to include
individual/group-level effects in the estimation. When |
allow_new_levels |
A flag indicating if new levels of group-level
effects are allowed (defaults to |
sample_new_levels |
Indicates how to sample new levels for grouping
factors specified in |
parameter |
A single character string or a character vector specifying
the growth parameter(s) to be estimated. Options include |
xrange |
An integer to set the predictor range (e.g., age) when
executing the interpolation via |
acg_velocity |
A real number specifying the percentage of peak growth
velocity to be used as the cessation velocity when estimating the
|
digits |
An integer (default |
numeric_cov_at |
An optional (named list) argument to specify the value
of continuous covariate(s). The default |
aux_variables |
An optional argument to specify the variable(s) that can
be passed to the |
levels_id |
An optional argument to specify the |
avg_reffects |
An optional argument (default |
idata_method |
A character string to indicate the interpolation method.
The number of interpolation points is set by the
|
ipts |
An integer to set the length of the predictor variable for
generating a smooth velocity curve. If |
seed |
An integer (default |
future |
A logical value (default |
future_session |
A character string specifying the session type when
|
future_splits |
A list (default
|
future_method |
A character string (default
|
future_re_expose |
A logical (default
|
usedtplyr |
A logical (default |
usecollapse |
A logical (default |
parallel |
A logical (default |
cores |
A positive integer (default |
average |
A logical value indicating whether to internally call the
|
plot |
A logical value specifying whether to plot comparisons by calling
the |
showlegends |
A logical value to specify whether to show legends
( |
variables |
A named list specifying the level 1 predictor, such as
|
deriv |
A numeric value specifying whether to estimate parameters based
on the differentiation of the distance curve or the model's first
derivative. Please refer to the |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
method |
A character string indicating whether to compute estimates
using the |
marginals |
A |
pdraws |
A character string (default
The |
pdrawso |
A character string (default
When |
pdrawsp |
A character string (default
When |
pdrawsh |
A character string (default
The summary of posterior draws for parameters is the default returned
object. The |
comparison |
A character string specifying the comparison type for
growth parameter estimation. Options are |
type |
string indicates the type (scale) of the predictions used to
compute contrasts or slopes. This can differ based on the model
type, but will typically be a string such as: "response", "link", "probs",
or "zero". When an unsupported string is entered, the model-specific list of
acceptable values is returned in an error message. When |
by |
Aggregate unit-level estimates (aka, marginalize, average over). Valid inputs:
|
bys |
A character string (default |
conf_level |
numeric value between 0 and 1. Confidence level to use to build a confidence interval. |
transform |
A function applied to individual draws from the posterior
distribution before computing summaries. The argument |
cross |
|
wts |
logical, string or numeric: weights to use when computing average predictions, contrasts or slopes. These weights only affect the averaging in
|
hypothesis |
specify a hypothesis test or custom contrast using a number , formula, string equation, vector, matrix, or function.
|
equivalence |
Numeric vector of length 2: bounds used for the two-one-sided test (TOST) of equivalence, and for the non-inferiority and non-superiority tests. See Details section below. |
eps |
NULL or numeric value which determines the step size to use when
calculating numerical derivatives: (f(x+eps)-f(x))/eps. When |
constrats_by |
A character vector (default |
constrats_at |
A named list (default |
constrats_subset |
A named list (default |
reformat |
A logical (default |
estimate_center |
A character string (default |
estimate_interval |
A character string (default |
dummy_to_factor |
A named list (default
|
verbose |
A logical argument (default |
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
funlist |
A list (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The growthparameters_comparison
function estimates and
returns the following growth parameters:
pgv
- peak growth velocity
apgv
- age at peak growth velocity
tgv
- takeoff growth velocity
atgv
- age at takeoff growth velocity
cgv
- cessation growth velocity
acgv
- age at cessation growth velocity
The takeoff growth velocity is the lowest velocity just before the peak
begins, indicating the start of the pubertal growth spurt. The cessation
growth velocity marks the end of the active pubertal growth spurt and is
calculated as a certain percentage of the peak velocity (pgv
).
Typically, 10 percent of pgv
is considered a good indicator for the
cessation of the active pubertal growth spurt (Hardin et al. 2022).
This percentage is controlled via the acg_velocity
argument, which
accepts a positive real value bounded between 0 and 1 (with the default value
being 0.1
, indicating 10 percent).
A data frame object with estimates and credible intervals (CIs) for
the computed parameter(s). The returned data frame includes the parameter
estimates, along with lower and upper bounds of the credible intervals,
typically labeled as Q2.5
and Q97.5
, assuming a 95%
confidence level. The specific columns may vary depending on the
computation method and the parameters being estimated.
Satpal Sandhu [email protected]
Hardin AM, Knigge RP, Oh HS, Valiathan M, Duren DL, McNulty KP, Middleton KM, Sherwood RJ (2022). “Estimating Craniofacial Growth Cessation: Comparison of Asymptote- and Rate-Based Methods.” The Cleft Palate Craniofacial Journal, 59(2), 230-238. doi:10.1177/10556656211002675, PMID: 33998905.
marginaleffects::comparisons()
marginaleffects::avg_comparisons()
marginaleffects::plot_comparisons()
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Note that since no covariate is part of the model fit, the below example # doesn't make sense and is included here only for the purpose of completeness. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit growthparameters_comparison(model, parameter = 'apgv', ndraws = 10)
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Note that since no covariate is part of the model fit, the below example # doesn't make sense and is included here only for the purpose of completeness. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit growthparameters_comparison(model, parameter = 'apgv', ndraws = 10)
The growthparameters() function estimates both
population-average and individual-specific growth parameters (e.g., age at
peak growth velocity). It also provides measures of uncertainty, including
standard errors (SE) and credible intervals (CIs). For a more advanced
analysis, consider using the growthparameters_comparison()
function,
which not only estimates adjusted parameters but also enables comparisons
of these parameters across different groups.
## S3 method for class 'bgmfit' growthparameters( model, newdata = NULL, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, summary = FALSE, robust = FALSE, transform = NULL, re_formula = NA, peak = TRUE, takeoff = FALSE, trough = FALSE, acgv = FALSE, acgv_velocity = 0.1, estimation_method = "fitted", allow_new_levels = FALSE, sample_new_levels = "uncertainty", incl_autocor = TRUE, numeric_cov_at = NULL, levels_id = NULL, avg_reffects = NULL, aux_variables = NULL, ipts = 10, deriv_model = TRUE, conf = 0.95, xrange = NULL, xrange_search = NULL, digits = 2, seed = 123, future = FALSE, future_session = "multisession", cores = NULL, parms_eval = FALSE, idata_method = NULL, parms_method = "getPeak", verbose = FALSE, fullframe = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) growthparameters(model, ...)
## S3 method for class 'bgmfit' growthparameters( model, newdata = NULL, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, summary = FALSE, robust = FALSE, transform = NULL, re_formula = NA, peak = TRUE, takeoff = FALSE, trough = FALSE, acgv = FALSE, acgv_velocity = 0.1, estimation_method = "fitted", allow_new_levels = FALSE, sample_new_levels = "uncertainty", incl_autocor = TRUE, numeric_cov_at = NULL, levels_id = NULL, avg_reffects = NULL, aux_variables = NULL, ipts = 10, deriv_model = TRUE, conf = 0.95, xrange = NULL, xrange_search = NULL, digits = 2, seed = 123, future = FALSE, future_session = "multisession", cores = NULL, parms_eval = FALSE, idata_method = NULL, parms_method = "getPeak", verbose = FALSE, fullframe = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) growthparameters(model, ...)
model |
An object of class |
newdata |
An optional data frame for estimation. If |
resp |
A character string (default |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
summary |
A logical value indicating whether only the estimate should be
computed ( |
robust |
A logical value to specify the summary options. If |
transform |
A function applied to individual draws from the posterior
distribution before computing summaries. The argument |
re_formula |
Option to indicate whether or not to include
individual/group-level effects in the estimation. When |
peak |
A logical value (default |
takeoff |
A logical value (default |
trough |
A logical value (default |
acgv |
A logical value (default |
acgv_velocity |
The percentage of the peak growth velocity to use when
estimating |
estimation_method |
A character string specifying the estimation method
when calculating the velocity from the posterior draws. The |
allow_new_levels |
A flag indicating if new levels of group-level
effects are allowed (defaults to |
sample_new_levels |
Indicates how to sample new levels for grouping
factors specified in |
incl_autocor |
A flag indicating if correlation structures originally
specified via |
numeric_cov_at |
An optional (named list) argument to specify the value
of continuous covariate(s). The default |
levels_id |
An optional argument to specify the |
avg_reffects |
An optional argument (default |
aux_variables |
An optional argument to specify the variable(s) that can
be passed to the |
ipts |
An integer to set the length of the predictor variable for
generating a smooth velocity curve. If |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
conf |
A numeric value (default |
xrange |
An integer to set the predictor range (e.g., age) when
executing the interpolation via |
xrange_search |
A vector of length two or a character string
|
digits |
An integer (default |
seed |
An integer (default |
future |
A logical value (default |
future_session |
A character string specifying the session type when
|
cores |
The number of cores to be used for parallel computations if
|
parms_eval |
A logical value to specify whether or not to compute growth parameters on the fly. This is for internal use only and is mainly needed for compatibility across internal functions. |
idata_method |
A character string to indicate the interpolation method.
The number of interpolation points is set by the
|
parms_method |
A character string specifying the method used when
evaluating |
verbose |
A logical argument (default |
fullframe |
A logical value indicating whether to return a
|
dummy_to_factor |
A named list (default
|
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
funlist |
A list (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The growthparameters() function internally calls either the
fitted_draws()
or the predict_draws()
function to estimate
first-derivative growth parameters for each posterior draw. The estimated
growth parameters include:
Age at Peak Growth Velocity (APGV)
Peak Growth Velocity (PGV)
Age at Takeoff Growth Velocity (ATGV)
Takeoff Growth Velocity (TGV)
Age at Cessation of Growth Velocity (ACGV)
Cessation Growth Velocity (CGV)
APGV and PGV are estimated using the sitar::getPeak()
function, while
ATGV and TGV are estimated using the sitar::getTakeoff()
function. The
sitar::getTrough()
function is employed to estimate ACGV and CGV. The
parameters from each posterior draw are then summarized to provide
estimates along with uncertainty measures (SEs and CIs).
Please note that estimating cessation and takeoff growth parameters may not be possible if there are no distinct pre-peak or post-peak troughs in the data.
A data frame with either five columns (when summary = TRUE
) or
two columns (when summary = FALSE
, assuming re_formual =
NULL
). The first two columns, common to both scenarios, are
'Parameter'
and 'Estimate'
, representing the growth parameter
(e.g., APGV, PGV) and its estimate. When summary = TRUE
, three
additional columns are included: 'Est.Error'
and two columns
representing the lower and upper bounds of the confidence intervals, named
Q.2.5
and Q.97.5
(for the 95% CI). If re_formual =
NULL
, an additional column with individual identifiers (e.g., id
)
is included.
Satpal Sandhu [email protected]
# Fit Bayesian SITAR Model # To avoid mode estimation, which takes time, the Bayesian SITAR model fit # to the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check if the model fit object 'berkeley_exfit' exists and load it berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average age and velocity during the peak growth spurt growthparameters(model, re_formula = NA) # Population average age and velocity during the take-off and peak # growth spurt (APGV, PGV, ATGV, TGV) growthparameters(model, re_formula = NA, peak = TRUE, takeoff = TRUE) # Individual-specific age and velocity during the take-off and peak # growth spurt (APGV, PGV, ATGV, TGV) growthparameters(model, re_formula = NULL, peak = TRUE, takeoff = TRUE)
# Fit Bayesian SITAR Model # To avoid mode estimation, which takes time, the Bayesian SITAR model fit # to the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check if the model fit object 'berkeley_exfit' exists and load it berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average age and velocity during the peak growth spurt growthparameters(model, re_formula = NA) # Population average age and velocity during the take-off and peak # growth spurt (APGV, PGV, ATGV, TGV) growthparameters(model, re_formula = NA, peak = TRUE, takeoff = TRUE) # Individual-specific age and velocity during the take-off and peak # growth spurt (APGV, PGV, ATGV, TGV) growthparameters(model, re_formula = NULL, peak = TRUE, takeoff = TRUE)
bgmfit
objectChecks if argument is a bgmfit
object
is.bgmfit(x)
is.bgmfit(x)
x |
An R object |
The loo_validation() function is a wrapper around the
brms::loo()
function to perform approximate leave-one-out cross-validation
based on the posterior likelihood. See brms::loo()
for more details.
## S3 method for class 'bgmfit' loo_validation( model, compare = TRUE, resp = NULL, dpar = NULL, pointwise = FALSE, moment_match = FALSE, reloo = FALSE, k_threshold = 0.7, save_psis = FALSE, moment_match_args = list(), reloo_args = list(), model_names = NULL, ndraws = NULL, draw_ids = NULL, cores = 1, deriv_model = NULL, verbose = FALSE, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, envir = NULL, ... ) loo_validation(model, ...)
## S3 method for class 'bgmfit' loo_validation( model, compare = TRUE, resp = NULL, dpar = NULL, pointwise = FALSE, moment_match = FALSE, reloo = FALSE, k_threshold = 0.7, save_psis = FALSE, moment_match_args = list(), reloo_args = list(), model_names = NULL, ndraws = NULL, draw_ids = NULL, cores = 1, deriv_model = NULL, verbose = FALSE, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, envir = NULL, ... ) loo_validation(model, ...)
model |
An object of class |
compare |
A logical flag indicating if the information criteria of the
models should be compared using |
resp |
Optional names of response variables. If specified, predictions are performed only for the specified response variables. |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
pointwise |
A flag indicating whether to compute the full
log-likelihood matrix at once or separately for each observation.
The latter approach is usually considerably slower but
requires much less working memory. Accordingly, if one runs
into memory issues, |
moment_match |
A logical flag to indicate whether
|
reloo |
A logical flag indicating whether |
k_threshold |
The Pareto |
save_psis |
Should the |
moment_match_args |
An optional |
reloo_args |
An optional |
model_names |
If |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
cores |
The number of cores to be used for parallel computations if
|
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
verbose |
A logical argument (default |
dummy_to_factor |
A named list (default
|
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The function supports model comparisons using loo::loo_compare()
for comparing information criteria across models. For bgmfit
objects, LOO
is simply an alias for loo
. Additionally, you
can use brms::add_criterion()
to store information criteria in the fitted
model object for later use.
If only one model object is provided, an object of class loo
is returned. If multiple objects are provided, an object of class
loolist
is returned.
Satpal Sandhu [email protected]
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Perform leave-one-out cross-validation loo_validation(model, cores = 1)
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Perform leave-one-out cross-validation loo_validation(model, cores = 1)
The marginal_comparison() function estimates and
compares growth curves such as distance and velocity. This function is a
wrapper around marginaleffects::comparisons()
and
marginaleffects::avg_comparisons()
. The marginaleffects::comparisons()
function computes unit-level (conditional) estimates, whereas
marginaleffects::avg_comparisons()
returns average (marginal) estimates.
A detailed explanation is available here.
Note that the marginaleffects package is highly flexible, and users
are expected to have a strong understanding of its workings. Additionally,
since the marginaleffects package is evolving rapidly, results from
the current implementation should be considered experimental.
## S3 method for class 'bgmfit' marginal_comparison( model, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, newdata = NULL, datagrid = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "gaussian", xrange = 1, digits = 2, numeric_cov_at = NULL, aux_variables = NULL, levels_id = NULL, avg_reffects = NULL, idata_method = NULL, ipts = NULL, seed = 123, future = FALSE, future_session = "multisession", future_splits = NULL, future_method = "future", future_re_expose = NULL, usedtplyr = FALSE, usecollapse = TRUE, cores = NULL, average = FALSE, plot = FALSE, showlegends = NULL, variables = NULL, deriv = NULL, deriv_model = NULL, method = "pkg", marginals = NULL, pdrawso = FALSE, pdrawsp = FALSE, pdrawsh = FALSE, comparison = "difference", type = NULL, by = FALSE, conf_level = 0.95, transform = NULL, cross = FALSE, wts = NULL, hypothesis = NULL, equivalence = NULL, eps = NULL, constrats_by = NULL, constrats_at = NULL, reformat = NULL, estimate_center = NULL, estimate_interval = NULL, dummy_to_factor = NULL, verbose = FALSE, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) marginal_comparison(model, ...)
## S3 method for class 'bgmfit' marginal_comparison( model, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, newdata = NULL, datagrid = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "gaussian", xrange = 1, digits = 2, numeric_cov_at = NULL, aux_variables = NULL, levels_id = NULL, avg_reffects = NULL, idata_method = NULL, ipts = NULL, seed = 123, future = FALSE, future_session = "multisession", future_splits = NULL, future_method = "future", future_re_expose = NULL, usedtplyr = FALSE, usecollapse = TRUE, cores = NULL, average = FALSE, plot = FALSE, showlegends = NULL, variables = NULL, deriv = NULL, deriv_model = NULL, method = "pkg", marginals = NULL, pdrawso = FALSE, pdrawsp = FALSE, pdrawsh = FALSE, comparison = "difference", type = NULL, by = FALSE, conf_level = 0.95, transform = NULL, cross = FALSE, wts = NULL, hypothesis = NULL, equivalence = NULL, eps = NULL, constrats_by = NULL, constrats_at = NULL, reformat = NULL, estimate_center = NULL, estimate_interval = NULL, dummy_to_factor = NULL, verbose = FALSE, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) marginal_comparison(model, ...)
model |
An object of class |
resp |
A character string (default |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
newdata |
An optional data frame for estimation. If |
datagrid |
A data frame or named list for setting up a custom grid of
predictor values to evaluate the quantities of interest. If |
re_formula |
Option to indicate whether or not to include
individual/group-level effects in the estimation. When |
allow_new_levels |
A flag indicating if new levels of group-level
effects are allowed (defaults to |
sample_new_levels |
Indicates how to sample new levels for grouping
factors specified in |
xrange |
An integer to set the predictor range (e.g., age) when
executing the interpolation via |
digits |
An integer (default |
numeric_cov_at |
An optional (named list) argument to specify the value
of continuous covariate(s). The default |
aux_variables |
An optional argument to specify the variable(s) that can
be passed to the |
levels_id |
An optional argument to specify the |
avg_reffects |
An optional argument (default |
idata_method |
A character string to indicate the interpolation method.
The number of interpolation points is set by the
|
ipts |
An integer to set the length of the predictor variable for
generating a smooth velocity curve. If |
seed |
An integer (default |
future |
A logical value (default |
future_session |
A character string specifying the session type when
|
future_splits |
A list (default
|
future_method |
A character string (default
|
future_re_expose |
A logical (default
|
usedtplyr |
A logical (default |
usecollapse |
A logical (default |
cores |
The number of cores to be used for parallel computations if
|
average |
A logical indicating whether to call
|
plot |
A logical indicating whether to plot the comparisons using
|
showlegends |
A logical value to specify whether to show legends
( |
variables |
A named list specifying the level 1 predictor, such as
|
deriv |
A numeric value indicating whether to estimate parameters based on the differentiation of the distance curve or the model's first derivative. |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
method |
A character string specifying whether to compute comparisons
using the marginaleffects machinery ( |
marginals |
A |
pdrawso |
A character string (default
When |
pdrawsp |
A character string (default
When |
pdrawsh |
A character string (default
The summary of posterior draws for parameters is the default returned
object. The |
comparison |
A character string specifying the comparison type for
growth parameter estimation. Options are |
type |
string indicates the type (scale) of the predictions used to
compute contrasts or slopes. This can differ based on the model
type, but will typically be a string such as: "response", "link", "probs",
or "zero". When an unsupported string is entered, the model-specific list of
acceptable values is returned in an error message. When |
by |
Aggregate unit-level estimates (aka, marginalize, average over). Valid inputs:
|
conf_level |
numeric value between 0 and 1. Confidence level to use to build a confidence interval. |
transform |
A function applied to individual draws from the posterior
distribution before computing summaries. The argument |
cross |
|
wts |
logical, string or numeric: weights to use when computing average predictions, contrasts or slopes. These weights only affect the averaging in
|
hypothesis |
specify a hypothesis test or custom contrast using a number , formula, string equation, vector, matrix, or function.
|
equivalence |
Numeric vector of length 2: bounds used for the two-one-sided test (TOST) of equivalence, and for the non-inferiority and non-superiority tests. See Details section below. |
eps |
NULL or numeric value which determines the step size to use when
calculating numerical derivatives: (f(x+eps)-f(x))/eps. When |
constrats_by |
A character vector (default |
constrats_at |
A character vector (default |
reformat |
A logical (default |
estimate_center |
A character string (default |
estimate_interval |
A character string (default |
dummy_to_factor |
A named list (default
|
verbose |
A logical argument (default |
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
funlist |
A list (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
A data frame with estimates and confidence intervals for the
specified parameters, or a list when method = 'custom'
and
hypothesis
is not NULL
.
Satpal Sandhu [email protected]
There are no references for Rd macro \insertAllCites
on this help page.
marginaleffects::comparisons()
,
marginaleffects::avg_comparisons()
,
marginaleffects::plot_comparisons()
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Note: Since no covariates are included in this model, the 'marginal_comparison' # function is being shown here as a dummy example. In practice, comparisons may # not make sense without relevant covariates. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Call marginal_comparison to demonstrate the function marginal_comparison(model, draw_ids = 1)
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Note: Since no covariates are included in this model, the 'marginal_comparison' # function is being shown here as a dummy example. In practice, comparisons may # not make sense without relevant covariates. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Call marginal_comparison to demonstrate the function marginal_comparison(model, draw_ids = 1)
The marginal_draws() function estimates and plots
growth curves (distance and velocity) by using the marginaleffects
package as a back-end. This function can compute growth curves (via
marginaleffects::predictions()
), average growth curves (via
marginaleffects::avg_predictions()
), or plot growth curves (via
marginaleffects::plot_predictions()
). Please see
here for details. Note that the
marginaleffects package is highly flexible, and therefore, it
is expected that the user has a strong understanding of its workings.
Furthermore, since marginaleffects is rapidly evolving, the
results obtained from the current implementation should be considered
experimental.
## S3 method for class 'bgmfit' marginal_draws( model, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, newdata = NULL, datagrid = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "gaussian", parameter = NULL, xrange = 1, acg_velocity = 0.1, digits = 2, numeric_cov_at = NULL, aux_variables = NULL, levels_id = NULL, avg_reffects = NULL, idata_method = NULL, ipts = NULL, seed = 123, future = FALSE, future_session = "multisession", future_splits = NULL, future_method = "future", future_re_expose = NULL, usedtplyr = FALSE, usecollapse = TRUE, cores = NULL, fullframe = FALSE, average = FALSE, plot = FALSE, showlegends = NULL, variables = NULL, condition = NULL, deriv = 0, deriv_model = TRUE, method = "custom", marginals = NULL, pdrawso = FALSE, pdrawsp = FALSE, pdrawsh = FALSE, type = NULL, by = NULL, conf_level = 0.95, transform = NULL, byfun = NULL, wts = NULL, hypothesis = NULL, equivalence = NULL, constrats_by = NULL, constrats_at = NULL, reformat = NULL, estimate_center = NULL, estimate_interval = NULL, dummy_to_factor = NULL, verbose = FALSE, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) marginal_draws(model, ...)
## S3 method for class 'bgmfit' marginal_draws( model, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, newdata = NULL, datagrid = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "gaussian", parameter = NULL, xrange = 1, acg_velocity = 0.1, digits = 2, numeric_cov_at = NULL, aux_variables = NULL, levels_id = NULL, avg_reffects = NULL, idata_method = NULL, ipts = NULL, seed = 123, future = FALSE, future_session = "multisession", future_splits = NULL, future_method = "future", future_re_expose = NULL, usedtplyr = FALSE, usecollapse = TRUE, cores = NULL, fullframe = FALSE, average = FALSE, plot = FALSE, showlegends = NULL, variables = NULL, condition = NULL, deriv = 0, deriv_model = TRUE, method = "custom", marginals = NULL, pdrawso = FALSE, pdrawsp = FALSE, pdrawsh = FALSE, type = NULL, by = NULL, conf_level = 0.95, transform = NULL, byfun = NULL, wts = NULL, hypothesis = NULL, equivalence = NULL, constrats_by = NULL, constrats_at = NULL, reformat = NULL, estimate_center = NULL, estimate_interval = NULL, dummy_to_factor = NULL, verbose = FALSE, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) marginal_draws(model, ...)
model |
An object of class |
resp |
A character string (default |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
newdata |
An optional data frame for estimation. If |
datagrid |
A grid of user-specified values to be used in the
|
re_formula |
Option to indicate whether or not to include
individual/group-level effects in the estimation. When |
allow_new_levels |
A flag indicating if new levels of group-level
effects are allowed (defaults to |
sample_new_levels |
Indicates how to sample new levels for grouping
factors specified in |
parameter |
A single character string or a character vector specifying
the growth parameter(s) to be estimated. Options include |
xrange |
An integer to set the predictor range (e.g., age) when
executing the interpolation via |
acg_velocity |
A real number specifying the percentage of peak growth
velocity to be used as the cessation velocity when estimating the
|
digits |
An integer (default |
numeric_cov_at |
An optional (named list) argument to specify the value
of continuous covariate(s). The default |
aux_variables |
An optional argument to specify the variable(s) that can
be passed to the |
levels_id |
An optional argument to specify the |
avg_reffects |
An optional argument (default |
idata_method |
A character string to indicate the interpolation method.
The number of interpolation points is set by the
|
ipts |
An integer to set the length of the predictor variable for
generating a smooth velocity curve. If |
seed |
An integer (default |
future |
A logical value (default |
future_session |
A character string specifying the session type when
|
future_splits |
A list (default
|
future_method |
A character string (default
|
future_re_expose |
A logical (default
|
usedtplyr |
A logical (default |
usecollapse |
A logical (default |
cores |
The number of cores to be used for parallel computations if
|
fullframe |
A logical value indicating whether to return a
|
average |
A logical indicating whether to internally call the
|
plot |
A logical specifying whether to plot predictions by calling
|
showlegends |
A logical value to specify whether to show legends
( |
variables |
A named list specifying the level 1 predictor, such as
|
condition |
Conditional predictions
|
deriv |
An integer to indicate whether to estimate the distance curve or
its derivative (i.e., velocity curve). The |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
method |
A character string specifying the computation method: whether
to use the marginaleffects machinery at the post-draw stage, i.e.,
|
marginals |
A |
pdrawso |
A character string (default
When |
pdrawsp |
A character string (default
When |
pdrawsh |
A character string (default
The summary of posterior draws for parameters is the default returned
object. The |
type |
string indicates the type (scale) of the predictions used to
compute contrasts or slopes. This can differ based on the model
type, but will typically be a string such as: "response", "link", "probs",
or "zero". When an unsupported string is entered, the model-specific list of
acceptable values is returned in an error message. When |
by |
Aggregate unit-level estimates (aka, marginalize, average over). Valid inputs:
|
conf_level |
numeric value between 0 and 1. Confidence level to use to build a confidence interval. |
transform |
A function applied to individual draws from the posterior
distribution before computing summaries. The argument |
byfun |
A function such as |
wts |
logical, string or numeric: weights to use when computing average predictions, contrasts or slopes. These weights only affect the averaging in
|
hypothesis |
specify a hypothesis test or custom contrast using a number , formula, string equation, vector, matrix, or function.
|
equivalence |
Numeric vector of length 2: bounds used for the two-one-sided test (TOST) of equivalence, and for the non-inferiority and non-superiority tests. See Details section below. |
constrats_by |
A character vector (default |
constrats_at |
A character vector (default |
reformat |
A logical (default |
estimate_center |
A character string (default |
estimate_interval |
A character string (default |
dummy_to_factor |
A named list (default
|
verbose |
A logical argument (default |
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
funlist |
A list (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The marginal_draws() function estimates fitted values (via
brms::fitted.brmsfit()
) or the posterior draws from the posterior
distribution (via brms::predict.brmsfit()
) depending on the type
argument.
An array of predicted mean response values. See brms::fitted.brmsfit for details.
Satpal Sandhu [email protected]
marginaleffects::predictions()
marginaleffects::avg_predictions()
marginaleffects::plot_predictions()
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance curve marginal_draws(model, deriv = 0, re_formula = NA) # Individual-specific distance curves marginal_draws(model, deriv = 0, re_formula = NULL) # Population average velocity curve marginal_draws(model, deriv = 1, re_formula = NA) # Individual-specific velocity curves marginal_draws(model, deriv = 1, re_formula = NULL)
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance curve marginal_draws(model, deriv = 0, re_formula = NA) # Individual-specific distance curves marginal_draws(model, deriv = 0, re_formula = NULL) # Population average velocity curve marginal_draws(model, deriv = 1, re_formula = NA) # Individual-specific velocity curves marginal_draws(model, deriv = 1, re_formula = NULL)
The optimization process for selecting the best-fitting SITAR
model involves choosing the optimal degrees of freedom (df
) for the
natural cubic spline curve, as well as determining the appropriate
transformations for the predictor (x
) and/or outcome (y
)
variables.
## S3 method for class 'bgmfit' optimize_model( model, newdata = NULL, optimize_df = NULL, optimize_x = list(NULL, log, sqrt), optimize_y = list(NULL, log, sqrt), transform_prior_class = NULL, transform_beta_coef = NULL, transform_sd_coef = NULL, exclude_default_funs = TRUE, add_fit_criteria = NULL, byresp = FALSE, model_name = NULL, overwrite = FALSE, file = NULL, force_save = FALSE, save_each = FALSE, digits = 2, cores = 1, verbose = FALSE, expose_function = NULL, usesavedfuns = FALSE, clearenvfuns = NULL, envir = NULL, ... ) optimize_model(model, ...)
## S3 method for class 'bgmfit' optimize_model( model, newdata = NULL, optimize_df = NULL, optimize_x = list(NULL, log, sqrt), optimize_y = list(NULL, log, sqrt), transform_prior_class = NULL, transform_beta_coef = NULL, transform_sd_coef = NULL, exclude_default_funs = TRUE, add_fit_criteria = NULL, byresp = FALSE, model_name = NULL, overwrite = FALSE, file = NULL, force_save = FALSE, save_each = FALSE, digits = 2, cores = 1, verbose = FALSE, expose_function = NULL, usesavedfuns = FALSE, clearenvfuns = NULL, envir = NULL, ... ) optimize_model(model, ...)
model |
An object of class |
newdata |
An optional data frame for estimation. If |
optimize_df |
A list of integers specifying the degrees of freedom
( |
optimize_x |
A list specifying the transformations for the predictor
variable (i.e., |
optimize_y |
A list specifying the transformations of the response
variable (i.e., |
transform_prior_class |
A character vector (default |
transform_beta_coef |
A character vector (default |
transform_sd_coef |
A character vector (default |
exclude_default_funs |
A logical indicating whether transformations for
( |
add_fit_criteria |
An optional argument (default |
byresp |
A logical (default |
model_name |
Optional name of the model. If |
overwrite |
Logical; Indicates if already stored fit
indices should be overwritten. Defaults to |
file |
Either |
force_save |
Logical; only relevant if |
save_each |
A logical (default |
digits |
An integer (default |
cores |
The number of cores to use in parallel processing (default
|
verbose |
A logical argument (default |
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
envir |
The environment used for function evaluation. The default is
|
... |
Other arguments passed to |
A list containing the optimized models of class bgmfit
, and
the the summary statistics if add_fit_criteria
are specified.
Satpal Sandhu [email protected]
# Fit Bayesian SITAR model # To avoid model estimation, which takes time, the Bayesian SITAR model fit # to the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # The following example shows a dummy call for optimization to save time. # Note that if the degree of freedom, and both the \code{optimize_x} and # \code{optimize_y} are \code{NULL} (i.e., nothing to optimize), the original # model object is returned. # To explicitly check whether the model is being optimized or not, # the user can set \code{verbose = TRUE}. This is useful for getting # information about what arguments have changed compared to the # original model. model2 <- optimize_model(model, optimize_df = NULL, optimize_x = NULL, optimize_y = NULL, verbose = TRUE)
# Fit Bayesian SITAR model # To avoid model estimation, which takes time, the Bayesian SITAR model fit # to the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # The following example shows a dummy call for optimization to save time. # Note that if the degree of freedom, and both the \code{optimize_x} and # \code{optimize_y} are \code{NULL} (i.e., nothing to optimize), the original # model object is returned. # To explicitly check whether the model is being optimized or not, # the user can set \code{verbose = TRUE}. This is useful for getting # information about what arguments have changed compared to the # original model. model2 <- optimize_model(model, optimize_df = NULL, optimize_x = NULL, optimize_y = NULL, verbose = TRUE)
Display conditional effects of one or more numeric and/or categorical predictors including two-way interaction effects.
## S3 method for class 'bgmfit' plot_conditional_effects( model, effects = NULL, conditions = NULL, int_conditions = NULL, re_formula = NA, spaghetti = FALSE, surface = FALSE, categorical = FALSE, ordinal = FALSE, method = "posterior_epred", transform = NULL, resolution = 100, select_points = 0, too_far = 0, prob = 0.95, robust = TRUE, newdata = NULL, ndraws = NULL, dpar = NULL, draw_ids = NULL, levels_id = NULL, resp = NULL, ipts = 10, deriv = 0, deriv_model = NULL, idata_method = NULL, verbose = FALSE, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) plot_conditional_effects(model, ...)
## S3 method for class 'bgmfit' plot_conditional_effects( model, effects = NULL, conditions = NULL, int_conditions = NULL, re_formula = NA, spaghetti = FALSE, surface = FALSE, categorical = FALSE, ordinal = FALSE, method = "posterior_epred", transform = NULL, resolution = 100, select_points = 0, too_far = 0, prob = 0.95, robust = TRUE, newdata = NULL, ndraws = NULL, dpar = NULL, draw_ids = NULL, levels_id = NULL, resp = NULL, ipts = 10, deriv = 0, deriv_model = NULL, idata_method = NULL, verbose = FALSE, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) plot_conditional_effects(model, ...)
model |
An object of class |
effects |
An optional character vector naming effects (main effects or
interactions) for which to compute conditional plots. Interactions are
specified by a |
conditions |
An optional |
int_conditions |
An optional named |
re_formula |
A formula containing group-level effects to be considered
in the conditional predictions. If |
spaghetti |
Logical. Indicates if predictions should
be visualized via spaghetti plots. Only applied for numeric
predictors. If |
surface |
Logical. Indicates if interactions or
two-dimensional smooths should be visualized as a surface.
Defaults to |
categorical |
Logical. Indicates if effects of categorical
or ordinal models should be shown in terms of probabilities
of response categories. Defaults to |
ordinal |
(Deprecated) Please use argument |
method |
Method used to obtain predictions. Can be set to
|
transform |
A function or a character string naming
a function to be applied on the predicted responses
before summary statistics are computed. Only allowed
if |
resolution |
Number of support points used to generate
the plots. Higher resolution leads to smoother plots.
Defaults to |
select_points |
Positive number.
Only relevant if |
too_far |
Positive number.
For surface plots only: Grid points that are too
far away from the actual data points can be excluded from the plot.
|
prob |
A value between 0 and 1 indicating the desired probability to be covered by the uncertainty intervals. The default is 0.95. |
robust |
If |
newdata |
An optional data frame for estimation. If |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
levels_id |
An optional argument to specify the |
resp |
A character string (default |
ipts |
An integer to set the length of the predictor variable for
generating a smooth velocity curve. If |
deriv |
An integer indicating whether to estimate the distance curve
or its derivative (velocity curve). The default |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
idata_method |
A character string to indicate the interpolation method.
The number of interpolation points is set by the
|
verbose |
A logical argument (default |
dummy_to_factor |
A named list (default
|
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
funlist |
A list (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The plot_conditional_effects() is a wrapper around the
brms::conditional_effects()
. The brms::conditional_effects()
function
from the brms package can be used to plot the fitted (distance) curve
when response (e.g., height) is not transformed. However, when the outcome
is log or square root transformed, the brms::conditional_effects()
will
return the fitted curve on the log or square root scale, whereas the
plot_conditional_effects() will return the fitted curve on the
original scale. Furthermore, the plot_conditional_effects() also
plots the velocity curve on the original scale after making the required
back-transformation. Apart from these differences, both these functions
(brms::conditional_effects and plot_conditional_effects()) work
in the same manner. In other words, the user can specify all the arguments
which are available in the brms::conditional_effects()
.
An object of class 'brms_conditional_effects'
, which is a
named list with one data.frame per effect containing all information
required to generate conditional effects plots. See
brms::conditional_effects()
for details.
Satpal Sandhu [email protected]
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance curve plot_conditional_effects(model, deriv = 0, re_formula = NA) # Individual-specific distance curves plot_conditional_effects(model, deriv = 0, re_formula = NULL) # Population average velocity curve plot_conditional_effects(model, deriv = 1, re_formula = NA) # Individual-specific velocity curves plot_conditional_effects(model, deriv = 1, re_formula = NULL)
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance curve plot_conditional_effects(model, deriv = 0, re_formula = NA) # Individual-specific distance curves plot_conditional_effects(model, deriv = 0, re_formula = NULL) # Population average velocity curve plot_conditional_effects(model, deriv = 1, re_formula = NA) # Individual-specific velocity curves plot_conditional_effects(model, deriv = 1, re_formula = NULL)
The plot_curves() function visualizes six different
types of growth curves using the ggplot2 package. Additionally, it
allows users to create customized plots from the data returned as a
data.frame
. For an alternative approach, the marginal_draws()
function can be used, which not only estimates adjusted curves but also
enables comparison across groups using the hypotheses
argument.
## S3 method for class 'bgmfit' plot_curves( model, opt = "dv", apv = FALSE, bands = NULL, conf = 0.95, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, newdata = NULL, summary = FALSE, digits = 2, re_formula = NULL, numeric_cov_at = NULL, aux_variables = NULL, levels_id = NULL, avg_reffects = NULL, ipts = 10, deriv_model = TRUE, xrange = NULL, xrange_search = NULL, takeoff = FALSE, trough = FALSE, acgv = FALSE, acgv_velocity = 0.1, seed = 123, estimation_method = "fitted", allow_new_levels = FALSE, sample_new_levels = "uncertainty", incl_autocor = TRUE, robust = FALSE, transform = NULL, future = FALSE, future_session = "multisession", cores = NULL, trim = 0, layout = "single", linecolor = NULL, linecolor1 = NULL, linecolor2 = NULL, label.x = NULL, label.y = NULL, legendpos = NULL, linetype.apv = NULL, linewidth.main = NULL, linewidth.apv = NULL, linetype.groupby = NA, color.groupby = NA, band.alpha = NULL, show_age_takeoff = TRUE, show_age_peak = TRUE, show_age_cessation = TRUE, show_vel_takeoff = FALSE, show_vel_peak = FALSE, show_vel_cessation = FALSE, returndata = FALSE, returndata_add_parms = FALSE, parms_eval = FALSE, idata_method = NULL, parms_method = "getPeak", verbose = FALSE, fullframe = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) plot_curves(model, ...)
## S3 method for class 'bgmfit' plot_curves( model, opt = "dv", apv = FALSE, bands = NULL, conf = 0.95, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, newdata = NULL, summary = FALSE, digits = 2, re_formula = NULL, numeric_cov_at = NULL, aux_variables = NULL, levels_id = NULL, avg_reffects = NULL, ipts = 10, deriv_model = TRUE, xrange = NULL, xrange_search = NULL, takeoff = FALSE, trough = FALSE, acgv = FALSE, acgv_velocity = 0.1, seed = 123, estimation_method = "fitted", allow_new_levels = FALSE, sample_new_levels = "uncertainty", incl_autocor = TRUE, robust = FALSE, transform = NULL, future = FALSE, future_session = "multisession", cores = NULL, trim = 0, layout = "single", linecolor = NULL, linecolor1 = NULL, linecolor2 = NULL, label.x = NULL, label.y = NULL, legendpos = NULL, linetype.apv = NULL, linewidth.main = NULL, linewidth.apv = NULL, linetype.groupby = NA, color.groupby = NA, band.alpha = NULL, show_age_takeoff = TRUE, show_age_peak = TRUE, show_age_cessation = TRUE, show_vel_takeoff = FALSE, show_vel_peak = FALSE, show_vel_cessation = FALSE, returndata = FALSE, returndata_add_parms = FALSE, parms_eval = FALSE, idata_method = NULL, parms_method = "getPeak", verbose = FALSE, fullframe = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) plot_curves(model, ...)
model |
An object of class |
opt |
A character string containing one or more of the following plotting options:
Note that 'd' and 'D' cannot be specified simultaneously, nor can 'v' and 'V'. Other combinations are allowed, e.g., 'dvau', 'Dvau', 'dVau', etc. |
apv |
A logical value (default |
bands |
A character string containing one or more of the following
options, or
The |
conf |
A numeric value (default |
resp |
A character string (default |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
newdata |
An optional data frame for estimation. If |
summary |
A logical value indicating whether only the estimate should be
computed ( |
digits |
An integer (default |
re_formula |
Option to indicate whether or not to include
individual/group-level effects in the estimation. When |
numeric_cov_at |
An optional (named list) argument to specify the value
of continuous covariate(s). The default |
aux_variables |
An optional argument to specify variables passed to the
|
levels_id |
An optional argument to specify the |
avg_reffects |
An optional argument (default |
ipts |
An integer to set the length of the predictor variable for
generating a smooth velocity curve. If |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
xrange |
An integer to set the predictor range (e.g., age) when
executing the interpolation via |
xrange_search |
A vector of length two or a character string
|
takeoff |
A logical value (default |
trough |
A logical value (default |
acgv |
A logical value (default |
acgv_velocity |
The percentage of the peak growth velocity to use when
estimating |
seed |
An integer (default |
estimation_method |
A character string specifying the estimation method
when calculating the velocity from the posterior draws. The |
allow_new_levels |
A flag indicating if new levels of group-level
effects are allowed (defaults to |
sample_new_levels |
Indicates how to sample new levels for grouping
factors specified in |
incl_autocor |
A flag indicating if correlation structures originally
specified via |
robust |
A logical value to specify the summary options. If |
transform |
A function applied to individual draws from the posterior
distribution before computing summaries. The argument |
future |
A logical value (default |
future_session |
A character string specifying the session type when
|
cores |
The number of cores to be used for parallel computations if
|
trim |
A numeric value (default |
layout |
A character string defining the plot layout. The default
|
linecolor |
The color of the lines when the layout is |
linecolor1 |
The color of the first line when the layout is
|
linecolor2 |
The color of the second line when the layout is
|
label.x |
An optional character string to label the x-axis. If
|
label.y |
An optional character string to label the y-axis. If
|
legendpos |
A character string to specify the position of the legend. If
|
linetype.apv |
A character string to specify the type of the vertical
line marking the APGV. Default |
linewidth.main |
A numeric value to specify the line width for distance
and velocity curves. The default |
linewidth.apv |
A numeric value to specify the width of the vertical
line marking the APGV. The default |
linetype.groupby |
A character string specifying the line type for
distance and velocity curves when drawing plots for a model with factor
covariates or individual-specific curves. The default is |
color.groupby |
A character string specifying the line color for
distance and velocity curves when drawing plots for a model with factor
covariates or individual-specific curves. The default is |
band.alpha |
A numeric value to specify the transparency of the CI bands
around the curves. The default |
show_age_takeoff |
A logical value (default |
show_age_peak |
A logical value (default |
show_age_cessation |
A logical value (default |
show_vel_takeoff |
A logical value (default |
show_vel_peak |
A logical value (default |
show_vel_cessation |
A logical value (default |
returndata |
A logical value (default |
returndata_add_parms |
A logical value (default |
parms_eval |
A logical value to specify whether or not to compute growth parameters on the fly. This is for internal use only and is mainly needed for compatibility across internal functions. |
idata_method |
A character string to indicate the interpolation method.
The number of interpolation points is set by the
|
parms_method |
A character string specifying the method used when
evaluating |
verbose |
A logical argument (default |
fullframe |
A logical value indicating whether to return a
|
dummy_to_factor |
A named list (default
|
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
funlist |
A list (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The plot_curves() function is a generic tool for visualizing the following six curves:
Population average distance curve
Population average velocity curve
Individual-specific distance curves
Individual-specific velocity curves
Unadjusted individual growth curves (i.e., observed growth curves)
Adjusted individual growth curves (adjusted for the model-estimated random effects)
Internally, plot_curves() calls the growthparameters()
function
to estimate and summarize the distance and velocity curves, as well as to
compute growth parameters such as the age at peak growth velocity (APGV).
The function also calls fitted_draws()
or predict_draws()
to make
inferences based on posterior draws. As a result, plot_curves()
can plot either fitted or predicted curves. For more details, see
fitted_draws()
and predict_draws()
to understand the difference between
fitted and predicted values.
A plot object (default) or a data.frame
when returndata
= TRUE
.
Satpal Sandhu [email protected]
growthparameters()
fitted_draws()
predict_draws()
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model is fit to # the 'berkeley_exdata' and saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance and velocity curves with default options plot_curves(model, opt = 'dv') # Individual-specific distance and velocity curves with default options # Note that \code{legendpos = 'none'} will suppress the legend positions. # This suppression is useful when plotting individual-specific curves plot_curves(model, opt = 'DV') # Population average distance and velocity curves with APGV plot_curves(model, opt = 'dv', apv = TRUE) # Individual-specific distance and velocity curves with APGV plot_curves(model, opt = 'DV', apv = TRUE) # Population average distance curve, velocity curve, and APGV with CI bands # To construct CI bands, growth parameters are first calculated for each # posterior draw and then summarized across draws. Therefore,summary # option must be set to FALSE plot_curves(model, opt = 'dv', apv = TRUE, bands = 'dvp', summary = FALSE) # Adjusted and unadjusted individual curves # Note ipts = NULL (i.e., no interpolation of predictor (i.e., age) to plot a # smooth curve). This is because it does not a make sense to interploate data # when estimating adjusted curves. Also, layout = 'facet' (and not default # layout = 'single') is used for the ease of visualizing the plotted # adjusted and unadjusted individual curves. However, these lines can be # superimposed on each other by setting the set layout = 'single'. # For other plots shown above, layout can be set as 'single' or 'facet' # Separate plots for adjusted and unadjusted curves (layout = 'facet') plot_curves(model, opt = 'au', ipts = NULL, layout = 'facet') # Superimposed adjusted and unadjusted curves (layout = 'single') plot_curves(model, opt = 'au', ipts = NULL, layout = 'single')
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model is fit to # the 'berkeley_exdata' and saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance and velocity curves with default options plot_curves(model, opt = 'dv') # Individual-specific distance and velocity curves with default options # Note that \code{legendpos = 'none'} will suppress the legend positions. # This suppression is useful when plotting individual-specific curves plot_curves(model, opt = 'DV') # Population average distance and velocity curves with APGV plot_curves(model, opt = 'dv', apv = TRUE) # Individual-specific distance and velocity curves with APGV plot_curves(model, opt = 'DV', apv = TRUE) # Population average distance curve, velocity curve, and APGV with CI bands # To construct CI bands, growth parameters are first calculated for each # posterior draw and then summarized across draws. Therefore,summary # option must be set to FALSE plot_curves(model, opt = 'dv', apv = TRUE, bands = 'dvp', summary = FALSE) # Adjusted and unadjusted individual curves # Note ipts = NULL (i.e., no interpolation of predictor (i.e., age) to plot a # smooth curve). This is because it does not a make sense to interploate data # when estimating adjusted curves. Also, layout = 'facet' (and not default # layout = 'single') is used for the ease of visualizing the plotted # adjusted and unadjusted individual curves. However, these lines can be # superimposed on each other by setting the set layout = 'single'. # For other plots shown above, layout can be set as 'single' or 'facet' # Separate plots for adjusted and unadjusted curves (layout = 'facet') plot_curves(model, opt = 'au', ipts = NULL, layout = 'facet') # Superimposed adjusted and unadjusted curves (layout = 'single') plot_curves(model, opt = 'au', ipts = NULL, layout = 'single')
Perform posterior predictive checks with the help of the bayesplot package.
## S3 method for class 'bgmfit' plot_ppc( model, type, ndraws = NULL, dpar = NULL, draw_ids = NULL, prefix = c("ppc", "ppd"), group = NULL, x = NULL, newdata = NULL, resp = NULL, size = 0.25, alpha = 0.7, trim = FALSE, bw = "nrd0", adjust = 1, kernel = "gaussian", n_dens = 1024, pad = TRUE, discrete = FALSE, binwidth = NULL, bins = NULL, breaks = NULL, freq = TRUE, y_draw = c("violin", "points", "both"), y_size = 1, y_alpha = 1, y_jitter = 0.1, verbose = FALSE, deriv_model = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, envir = NULL, ... ) plot_ppc(model, ...)
## S3 method for class 'bgmfit' plot_ppc( model, type, ndraws = NULL, dpar = NULL, draw_ids = NULL, prefix = c("ppc", "ppd"), group = NULL, x = NULL, newdata = NULL, resp = NULL, size = 0.25, alpha = 0.7, trim = FALSE, bw = "nrd0", adjust = 1, kernel = "gaussian", n_dens = 1024, pad = TRUE, discrete = FALSE, binwidth = NULL, bins = NULL, breaks = NULL, freq = TRUE, y_draw = c("violin", "points", "both"), y_size = 1, y_alpha = 1, y_jitter = 0.1, verbose = FALSE, deriv_model = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, envir = NULL, ... ) plot_ppc(model, ...)
model |
An object of class |
type |
Type of the ppc plot as given by a character string.
See |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
prefix |
The prefix of the bayesplot function to be applied. Either '"ppc"' (posterior predictive check; the default) or '"ppd"' (posterior predictive distribution), the latter being the same as the former except that the observed data is not shown for '"ppd"'. |
group |
Optional name of a factor variable in the model
by which to stratify the ppc plot. This argument is required for
ppc |
x |
Optional name of a variable in the model.
Only used for ppc types having an |
newdata |
An optional data frame for estimation. If |
resp |
A character string (default |
size , alpha
|
Passed to the appropriate geom to control the appearance of the predictive distributions. |
trim |
A logical scalar passed to |
bw , adjust , kernel , n_dens
|
Optional arguments passed to
|
pad |
A logical scalar passed to |
discrete |
For |
binwidth |
Passed to |
bins |
Passed to |
breaks |
Passed to |
freq |
For histograms, |
y_draw |
For |
y_jitter , y_size , y_alpha
|
For |
verbose |
A logical argument (default |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
dummy_to_factor |
A named list (default
|
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The plot_ppc() function is a wrapper around the
brms::pp_check()
function, which allows for the visualization of
posterior predictive checks.
A ggplot
object that can be further customized using the
ggplot2 package.
Satpal Sandhu [email protected]
# Fit Bayesian SITAR model # To avoid mode estimation, which takes time, the Bayesian SITAR model is fit to # the 'berkeley_exdata' and saved as an example fit ('berkeley_exfit'). # See the 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit plot_ppc(model, ndraws = 100)
# Fit Bayesian SITAR model # To avoid mode estimation, which takes time, the Bayesian SITAR model is fit to # the 'berkeley_exdata' and saved as an example fit ('berkeley_exfit'). # See the 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit plot_ppc(model, ndraws = 100)
The predict_draws() function is a wrapper around the
brms::predict.brmsfit()
function, which obtains predicted values (and
their summary) from the posterior distribution. See
brms::predict.brmsfit()
for details.
## S3 method for class 'bgmfit' predict_draws( model, newdata = NULL, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "uncertainty", incl_autocor = TRUE, numeric_cov_at = NULL, levels_id = NULL, avg_reffects = NULL, aux_variables = NULL, ipts = 10, deriv = 0, deriv_model = TRUE, summary = TRUE, robust = FALSE, transform = NULL, probs = c(0.025, 0.975), xrange = NULL, xrange_search = NULL, parms_eval = FALSE, parms_method = "getPeak", idata_method = NULL, verbose = FALSE, fullframe = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) predict_draws(model, ...)
## S3 method for class 'bgmfit' predict_draws( model, newdata = NULL, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, re_formula = NA, allow_new_levels = FALSE, sample_new_levels = "uncertainty", incl_autocor = TRUE, numeric_cov_at = NULL, levels_id = NULL, avg_reffects = NULL, aux_variables = NULL, ipts = 10, deriv = 0, deriv_model = TRUE, summary = TRUE, robust = FALSE, transform = NULL, probs = c(0.025, 0.975), xrange = NULL, xrange_search = NULL, parms_eval = FALSE, parms_method = "getPeak", idata_method = NULL, verbose = FALSE, fullframe = NULL, dummy_to_factor = NULL, expose_function = FALSE, usesavedfuns = NULL, clearenvfuns = NULL, funlist = NULL, envir = NULL, ... ) predict_draws(model, ...)
model |
An object of class |
newdata |
An optional data frame for estimation. If |
resp |
A character string (default |
dpar |
Optional name of a predicted distributional parameter. If specified, expected predictions of this parameters are returned. |
ndraws |
A positive integer indicating the number of posterior draws to
use in estimation. If |
draw_ids |
An integer specifying the specific posterior draw(s) to use
in estimation (default |
re_formula |
Option to indicate whether or not to include
individual/group-level effects in the estimation. When |
allow_new_levels |
A flag indicating if new levels of group-level
effects are allowed (defaults to |
sample_new_levels |
Indicates how to sample new levels for grouping
factors specified in |
incl_autocor |
A flag indicating if correlation structures originally
specified via |
numeric_cov_at |
An optional (named list) argument to specify the value
of continuous covariate(s). The default |
levels_id |
An optional argument to specify the |
avg_reffects |
An optional argument (default |
aux_variables |
An optional argument to specify the variable(s) that can
be passed to the |
ipts |
An integer to set the length of the predictor variable for
generating a smooth velocity curve. If |
deriv |
An integer indicating whether to estimate the distance curve
or its derivative (velocity curve). The default |
deriv_model |
A logical value specifying whether to estimate the
velocity curve from the derivative function or by differentiating the
distance curve. Set |
summary |
A logical value indicating whether only the estimate should be
computed ( |
robust |
A logical value to specify the summary options. If |
transform |
A function applied to individual draws from the posterior
distribution before computing summaries. The argument |
probs |
The percentiles to be computed by the |
xrange |
An integer to set the predictor range (e.g., age) when
executing the interpolation via |
xrange_search |
A vector of length two or a character string
|
parms_eval |
A logical value to specify whether or not to compute growth parameters on the fly. This is for internal use only and is mainly needed for compatibility across internal functions. |
parms_method |
A character string specifying the method used when
evaluating |
idata_method |
A character string to indicate the interpolation method.
The number of interpolation points is set by the
|
verbose |
A logical argument (default |
fullframe |
A logical value indicating whether to return a
|
dummy_to_factor |
A named list (default
|
expose_function |
A logical argument (default |
usesavedfuns |
A logical value (default |
clearenvfuns |
A logical value indicating whether to clear the exposed
Stan functions from the environment ( |
funlist |
A list (default |
envir |
The environment used for function evaluation. The default is
|
... |
Additional arguments passed to the |
The predict_draws() function computes the fitted values
from the posterior distribution. The brms::predict.brmsfit()
function
from the brms package can be used to obtain predicted (distance)
values when the outcome (e.g., height) is untransformed. However, when the
outcome is log or square root transformed, the brms::predict.brmsfit()
function will return the fitted curve on the log or square root scale. In
contrast, the predict_draws() function returns the fitted values
on the original scale. Furthermore, predict_draws() also computes
the first derivative (velocity), again on the original scale, after making
the necessary back-transformation. Aside from these differences, both
functions (brms::predict.brmsfit()
and predict_draws()) work
similarly. In other words, the user can specify all the options available
in brms::predict.brmsfit()
.
An array of predicted response values. See brms::predict.brmsfit()
for details.
Satpal Sandhu [email protected]
# Fit Bayesian SITAR model # To avoid mode estimation, which takes time, the Bayesian SITAR model is fit # to the 'berkeley_exdata' and saved as an example fit ('berkeley_exfit'). # See the 'bsitar' function for details on 'berkeley_exdata' and # berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance curve predict_draws(model, deriv = 0, re_formula = NA) # Individual-specific distance curves predict_draws(model, deriv = 0, re_formula = NULL) # Population average velocity curve predict_draws(model, deriv = 1, re_formula = NA) # Individual-specific velocity curves predict_draws(model, deriv = 1, re_formula = NULL)
# Fit Bayesian SITAR model # To avoid mode estimation, which takes time, the Bayesian SITAR model is fit # to the 'berkeley_exdata' and saved as an example fit ('berkeley_exfit'). # See the 'bsitar' function for details on 'berkeley_exdata' and # berkeley_exfit'. # Check and confirm whether the model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Population average distance curve predict_draws(model, deriv = 0, re_formula = NA) # Individual-specific distance curves predict_draws(model, deriv = 0, re_formula = NULL) # Population average velocity curve predict_draws(model, deriv = 1, re_formula = NA) # Individual-specific velocity curves predict_draws(model, deriv = 1, re_formula = NULL)
The update_model() function is a wrapper around the
update()
function from the brms package, which refits the model
based on the user-specified updated arguments.
## S3 method for class 'bgmfit' update_model( model, newdata = NULL, recompile = NULL, expose_function = FALSE, verbose = FALSE, check_newargs = FALSE, envir = NULL, ... ) update_model(model, ...)
## S3 method for class 'bgmfit' update_model( model, newdata = NULL, recompile = NULL, expose_function = FALSE, verbose = FALSE, check_newargs = FALSE, envir = NULL, ... ) update_model(model, ...)
model |
An object of class |
newdata |
An optional |
recompile |
A logical value indicating whether the Stan model should be
recompiled. When |
expose_function |
A logical argument (default |
verbose |
A logical argument (default |
check_newargs |
A logical value (default |
envir |
The environment used for function evaluation. The default is
|
... |
Other arguments passed to |
This function is an adapted version of the update() function from the brms package.
An updated object of class brmsfit
.
Satpal Sandhu [email protected]
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Update model # Note that in case all arguments supplied to the update_model() call are # same as the original model fit (checked via check_newargs = TRUE), then # original model object is returned. # To explicitly get this information whether model is being updated or not, # user can set verbose = TRUE. The verbose = TRUE also useful in getting the # information regarding what all arguments have been changed as compared to # the original model. model2 <- update_model(model, df = 5, check_newargs = TRUE, verbose = TRUE)
# Fit Bayesian SITAR model # To avoid mode estimation which takes time, the Bayesian SITAR model fit to # the 'berkeley_exdata' has been saved as an example fit ('berkeley_exfit'). # See 'bsitar' function for details on 'berkeley_exdata' and 'berkeley_exfit'. # Check and confirm whether model fit object 'berkeley_exfit' exists berkeley_exfit <- getNsObject(berkeley_exfit) model <- berkeley_exfit # Update model # Note that in case all arguments supplied to the update_model() call are # same as the original model fit (checked via check_newargs = TRUE), then # original model object is returned. # To explicitly get this information whether model is being updated or not, # user can set verbose = TRUE. The verbose = TRUE also useful in getting the # information regarding what all arguments have been changed as compared to # the original model. model2 <- update_model(model, df = 5, check_newargs = TRUE, verbose = TRUE)