Package {JointAI}


Version: 1.2.0
Title: Joint Analysis and Imputation of Incomplete Data
Description: Joint analysis and imputation of incomplete data in the Bayesian framework, using (generalized) linear (mixed) models and extensions thereof, survival models, or joint models for longitudinal and survival data, as described in Erler, Rizopoulos and Lesaffre (2021) <doi:10.18637/jss.v100.i20>. Incomplete covariates, if present, are automatically imputed. The package performs some preprocessing of the data and creates a 'JAGS' model, which will then automatically be passed to 'JAGS' https://mcmc-jags.sourceforge.io/ with the help of the package 'rjags'.
URL: https://nerler.github.io/JointAI/
License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]
BugReports: https://github.com/nerler/JointAI/issues/
LazyData: TRUE
Imports: rjags, mcmcse, coda, rlang, future, mathjaxr, survival
SystemRequirements: JAGS (https://mcmc-jags.sourceforge.io/)
Suggests: knitr, rmarkdown, bookdown, foreign, ggplot2, corrplot, ggpubr, svglite, testthat, tibble
VignetteBuilder: knitr
Encoding: UTF-8
RdMacros: mathjaxr
Config/testthat/edition: 3
Language: en-GB
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-12-02 09:38:22 UTC; nerler
Author: Nicole S. Erler ORCID iD [aut, cre]
Maintainer: Nicole S. Erler <n.s.erler@umcutrecht.nl>
Repository: CRAN
Date/Publication: 2026-12-02 10:10:02 UTC

JointAI: Joint Analysis and Imputation of Incomplete Data

Description

The JointAI package performs simultaneous imputation and inference for incomplete or complete data under the Bayesian framework. Models for incomplete covariates, conditional on other covariates, are specified automatically and modelled jointly with the analysis model. MCMC sampling is performed in 'JAGS' via the R package rjags.

Main functions

JointAI provides the following main functions that facilitate analysis with different models:

As far as possible, the specification of these functions is analogous to the specification of widely used functions for the analysis of complete data, such as lm, glm, lme (from the package nlme), survreg (from the package survival) and coxph (from the package survival).

Computations can be performed in parallel to reduce computational time, using the package future, the argument shrinkage allows the user to impose a penalty on the regression coefficients of some or all models involved, and hyper-parameters can be changed via the argument hyperpars.

To obtain summaries of the results, the functions summary(), coef() and confint() are available, and results can be visualized with the help of traceplot() or densplot().

The function predict() allows prediction (including credible intervals) from JointAI models.

Evaluation and export

Two criteria for evaluation of convergence and precision of the posterior estimate are available:

Imputed data can be extracted (and exported to SPSS) using get_MIdat(). The function plot_imp_distr() allows visual comparison of the distribution of observed and imputed values.

Other useful functions

Vignettes

The following vignettes are available

Author(s)

Maintainer: Nicole S. Erler n.s.erler@umcutrecht.nl (ORCID)

Authors:

References

Erler NS, Rizopoulos D, Lesaffre EMEH (2021). "JointAI: Joint Analysis and Imputation of Incomplete Data in R." Journal of Statistical Software, 100(20), 1-56. doi:10.18637/jss.v100.i20.

Erler, N.S., Rizopoulos, D., Rosmalen, J., Jaddoe, V.W.V., Franco, O. H., & Lesaffre, E.M.E.H. (2016). Dealing with missing covariates in epidemiologic studies: A comparison between multiple imputation and a full Bayesian approach. Statistics in Medicine, 35(17), 2955-2974. doi:10.1002/sim.6944

Erler, N.S., Rizopoulos D., Jaddoe, V.W.V., Franco, O.H. & Lesaffre, E.M.E.H. (2019). Bayesian imputation of time-varying covariates in linear mixed models. Statistical Methods in Medical Research, 28(2), 555–568. doi:10.1177/0962280217730851

See Also

Useful links:


Gelman-Rubin criterion for convergence

Description

Calculates the Gelman-Rubin criterion for convergence (uses gelman.diag from package coda).

Usage

GR_crit(object, confidence = 0.95, transform = FALSE, autoburnin = TRUE,
  multivariate = TRUE, subset = NULL, exclude_chains = NULL,
  start = NULL, end = NULL, thin = NULL, warn = TRUE, mess = TRUE,
  ...)

Arguments

object

object inheriting from class 'JointAI'

confidence

the coverage probability of the confidence interval for the potential scale reduction factor

transform

a logical flag indicating whether variables in x should be transformed to improve the normality of the distribution. If set to TRUE, a log transform or logit transform, as appropriate, will be applied.

autoburnin

a logical flag indicating whether only the second half of the series should be used in the computation. If set to TRUE (default) and start(x) is less than end(x)/2 then start of series will be adjusted so that only second half of series is used.

multivariate

a logical flag indicating whether the multivariate potential scale reduction factor should be calculated for multivariate chains

subset

subset of parameters/variables/nodes (columns in the MCMC sample). Follows the same principle as the argument monitor_params in *_imp.

exclude_chains

optional vector of the index numbers of chains that should be excluded

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

warn

logical; should warnings be given? Default is TRUE.

mess

logical; should messages be given? Default is TRUE.

...

currently not used

Value

An object of class gelman.diag (see gelman.diag): a list with elements psrf, a matrix with the point estimate and upper confidence limit of the potential scale reduction factor for each selected parameter, and mpsrf, the multivariate potential scale reduction factor (NULL unless multivariate = TRUE and more than one parameter is selected).

References

Gelman, A and Rubin, DB (1992) Inference from iterative simulation using multiple sequences, Statistical Science, 7, 457-511.

Brooks, SP. and Gelman, A. (1998) General methods for monitoring convergence of iterative simulations. Journal of Computational and Graphical Statistics, 7, 434-455.

See Also

The vignette Parameter Selection contains some examples how to specify the argument subset.

Examples

mod1 <- lm_imp(y ~ C1 + C2 + M2, data = wideDF, n.iter = 100)
GR_crit(mod1)




Fitted object of class 'JointAI'

Description

An object returned by one of the main functions *_imp.

Value

analysis_type

lm, glm, clm, lme, glme, clmm, survreg or coxph (with attributes family and link for GLM-type models

formula

The formula used in the (analysis) model.

data

original (incomplete, but pre-processed) data

models

named vector specifying the the types of all sub-models

fixed

a list of the fixed effects formulas of the sub-model(s) for which the use had specified a formula

random

a list of the random effects formulas of the sub-model(s) for which the use had specified a formula

Mlist

a list (for internal use) containing the data and information extracted from the data and model formulas, split up into

  • a named vector identifying the levels (in the hierarchy) of all variables (Mlvls)

  • a vector of the id variables that were extracted from the random effects formulas (idvar)

  • a list of grouping information for each grouping level of the data (groups)

  • a named vector identifying the hierarchy of the grouping levels (group_lvls)

  • a named vector giving the number of observations on each level of the hierarchy (N)

  • the name of the time variable (only for survival models with time-varying covariates) (timevar)

  • a formula of auxiliary variables (auxvars)

  • a list specifying the reference categories and dummy variables for all factors involved in the models (refs)

  • a list of linear predictor information (column numbers per design matrix) for all sub-models (lp_cols)

  • a list identifying information for interaction terms found in the model formulas (interactions)

  • a data.frame containing information on transformations of incomplete variables (trafos)

  • a data.frame containing information on transformations of all variables (fcts_all)

  • a logical indicator if parameter for posterior predictive checks should be monitored (ppc; not yet used)

  • a vector specifying if shrinkage of regression coefficients should be performed, and if so for which models and what type of shrinkage (shrinkage)

  • the number of degrees of freedom to be used in the spline specification of the baseline hazard in proportional hazards survival models (df_basehaz)

  • a list of matrices, one per level of the data, specifying centring and scaling parameters for the data (scale_pars)

  • a list containing information on the outcomes (mostly relevant for survival outcomes; outcomes)

  • a list of terms objects, needed to be able to build correct design matrices for the Gauss-Kronrod quadrature when, for example, splines are used to model time in a joint model (terms_list)

par_index_main

a list of matrices specifying the indices of the regression coefficients for each of the main models per design matrix

par_index_other

a list of matrices specifying the indices of regression coefficients for each covariate model per design matrix

jagsmodel

The JAGS model as character string.

mcmc_settings

a list containing MCMC sampling related information with elements

modelfile:

path and name of the JAGS model file

n.chains:

number of MCMC chains

n.adapt:

number of iterations in the adaptive phase

n.iter:

number of iterations in the MCMC sample

variable.names:

monitored nodes

thin:

thinning interval of the MCMC sample

inits:

a list containing the initial values that were passed to rjags

keep_scaled_mcmc:

TRUE if the MCMC sample on the scale used in JAGS is kept (only present in that case)

monitor_params

the named list of parameter groups to be monitored

data_list

list with data that was passed to rjags

hyperpars

a list containing the values of the hyper-parameters used

info_list

a list with information used to write the imputation model syntax

coef_list

a list relating the regression coefficient vectors used in the JAGS model to the names of the corresponding covariates

model

the JAGS model (an object of class 'jags', created by rjags)

sample

MCMC sample on the sampling scale (included only if keep_scaled_sample = TRUE)

MCMC

MCMC sample, scaled back to the scale of the data

comp_info

a list with information on the computational setting (start_time: date and time the calculation was started, duration: computational time of the model adaptive and sampling phase, JointAI_version: package version, R_version: the R.version.string, parallel: whether parallel computation was used, workers: if parallel computation was used, the number of workers)

fitted.values

fitted/predicted values (if available)

residuals

residuals (if available)

call

the original call


Calculate and plot the Monte Carlo error

Description

Calculate, print and plot the Monte Carlo error of the samples from a 'JointAI' model, combining the samples from all MCMC chains.

Usage

MC_error(x, subset = NULL, exclude_chains = NULL, start = NULL,
  end = NULL, thin = NULL, digits = 2, warn = TRUE, mess = TRUE, ...)

## S3 method for class 'MCElist'
plot(x, data_scale = TRUE, plotpars = NULL,
  ablinepars = list(v = 0.05), minlength = 20, ...)

Arguments

x

object inheriting from class 'JointAI'

subset

subset of parameters/variables/nodes (columns in the MCMC sample). Follows the same principle as the argument monitor_params in *_imp.

exclude_chains

optional vector of the index numbers of chains that should be excluded

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

digits

number of digits for the printed output

warn

logical; should warnings be given? Default is TRUE.

mess

logical; should messages be given? Default is TRUE.

...

Arguments passed on to mcmcse::mcse.mat

size

represents the batch size in “bm” and the truncation point in “bartlett” and “tukey”. Default is NULL which implies that an optimal batch size is calculated using the batchSize function. Can take character values of “sqroot” and “cuberoot” or any numeric value between 1 and n/2. “sqroot” means size is \lfloor n^{1/2} \rfloor and “cuberoot” means size is \lfloor n^{1/3} \rfloor.

g

a function such that E(g(x)) is the quantity of interest. The default is NULL, which causes the identity function to be used.

method

any of “bm”,“obm”,“bartlett”, “tukey”. “bm” represents batch means estimator, “obm” represents overlapping batch means estimator with, “bartlett” and “tukey” represents the modified-Bartlett window and the Tukey-Hanning windows for spectral variance estimators.

r

The lugsail parameters (r) that converts a lag window into its lugsail equivalent. Larger values of r will typically imply less underestimation of “cov”, but higher variability of the estimator. Default is r = 3 and r = 1,2 are also good choices although may lead to underestimates of the variance. r > 5 is not recommended.

data_scale

logical; show the Monte Carlo error of the sample transformed back to the scale of the data (TRUE) or on the sampling scale (this requires the argument keep_scaled_mcmc = TRUE to be set when fitting the model)

plotpars

optional; list of parameters passed to plot()

ablinepars

optional; list of parameters passed to abline()

minlength

number of characters the variable names are abbreviated to

Value

An object of class MCElist with elements data_scale, sampling_scale and digits. The first two are matrices with one row per selected node and columns est (posterior mean), MCSE (Monte Carlo error), SD (posterior standard deviation) and MCSE/SD (Monte Carlo error divided by post. standard deviation), for the MCMC sample transformed back to the scale of the data and for the sample on the scale used in JAGS. sampling_scale is NULL unless the model was fitted with keep_scaled_mcmc = TRUE.

Functions

Note

Lesaffre & Lawson (2012; p. 195) suggest the Monte Carlo error of a parameter should not be more than 5% of the posterior standard deviation of this parameter (i.e., MCSE/SD \le 0.05).

Long variable names:
The default plot margins may not be wide enough when variable names are longer than a few characters. The plot margin can be adjusted (globally) using the argument "mar" in par.

References

Lesaffre, E., & Lawson, A. B. (2012). Bayesian Biostatistics. John Wiley & Sons.

See Also

The vignette Parameter Selection provides some examples how to specify the argument subset.

Examples


## Not run: 

mod <- lm_imp(y ~ C1 + C2 + M2, data = wideDF, n.iter = 100)

MC_error(mod)

plot(MC_error(mod), ablinepars = list(lty = 2),
     plotpars = list(pch = 19, col = 'blue'))

## End(Not run)


National Health and Nutrition Examination Survey (NHANES) Data

Description

This data is a small subset of the data collected within the 2011-2012 wave of the NHANES study, a study designed to assess the health and nutritional status of adults and children in the United States, conduced by the National Center for Health Statistics.

Usage

data(NHANES)

Format

A data frame with 186 rows and 13 variables:

SBP

systolic blood pressure

gender

male or female

age

in years

race

race / Hispanic origin (5 categories)

WC

waist circumference in cm

alc

alcohol consumption (binary: <1 drink per week vs. >= 1 drink per week)

educ

educational level (binary: low vs. high)

creat

creatinine concentration in mg/dL

albu

albumin concentration in g/dL

uricacid

uric acid concentration in mg/dL

bili

bilirubin concentration in mg/dL

occup

occupational status (3 categories)

smoke

smoking status (3 ordered categories)

Note

The subset provided here was selected and re-coded to facilitate demonstration of the functionality of the JointAI package, and no clinical conclusions should be derived from it.

Source

National Center for Health Statistics (NCHS) (2011 - 2012). National Health and Nutrition Examination Survey Data. URL https://www.cdc.gov/nchs/nhanes/.

Examples

summary(NHANES)

PBC data

Description

Data from the Mayo Clinic trial in primary biliary cirrhosis (PBC) of the liver. This dataset was obtained from the survival package: the variables copper and trig from survival::pbc were merged into survival::pbcseq and several categorical variables were re-coded.

Format

PBC: A data frame of 312 individuals in long format with 1945 rows and 21 variables.

Survival outcome and id

id

case number

futime

number of days between registration and the earlier of death, transplantation, or end of follow-up

status

status at endpoint ("censored", "transplant" or "dead")

Baseline covariates

trt

D-pen (D-penicillamine) vs placebo

age

in years

sex

male or female

copper

urine copper (\mug/day)

trig

triglycerides (mg/dl)

Time-varying covariates

day

number of days between enrolment and this visit date; all measurements below refer to this date

albumin

serum albumin (mg/dl)

alk.phos

alkaline phosphatase (U/liter)

ascites

presence of ascites

ast

aspartate aminotransferase (U/ml)

bili

serum bilirubin (mg/dl)

chol

serum cholesterol (mg/dl)

edema

"no": no oedema, "(un)treated": untreated or successfully treated 1 oedema, "edema": oedema despite diuretic therapy

hepato

presence of hepatomegaly (enlarged liver)

platelet

platelet count

protime

standardised blood clotting time

spiders

blood vessel malformations in the skin

stage

histologic stage of disease (4 levels)

Examples

 summary(PBC)


Create a Survival Object

Description

This function just calls Surv() from the survival package.

Usage

Surv(time, time2, event, type = c("right", "left", "interval", "counting",
  "interval2"), origin = 0)

Arguments

time

for right censored data, this is the follow up time. For interval data, the first argument is the starting time for the interval.

time2

ending time of the interval for interval censored or counting process data only. Intervals are assumed to be open on the left and closed on the right, (start, end]. For counting process data, event indicates whether a transtion to another state occurred at the end of the interval.

event

The status indicator, normally 0=alive, 1=dead. Other choices are TRUE/FALSE (TRUE = death), 1/2 (2=death), or a factor variable. For interval censored data, the status indicator is 0=right censored, 1=event at time, 2=left censored, 3=interval censored. For multiple endpoint data the event variable will always be a factor, whose first level must correspond to "no observed transtition for this subject at this time point". There is no constraint on the labels of the factor; "none", "censored", and "alive" are common choices for the first level. Although unusual, the event indicator can be omitted, in which case all subjects are assumed to have an event.

type

character string specifying the type of censoring. Possible values are "right", "left", "counting", "interval", "interval2". The default is multi-state if event is a factor, counting process if time2 is present, or right censored, in that order.

origin

for counting process data, the hazard function origin. This option was intended to be used in conjunction with a model containing time dependent strata in order to align the subjects properly when they cross over from one strata to another, but it has rarely proven useful and is depricated.


Add initial values for nodes that JAGS >= 5 cannot initialise

Description

JAGS >= 5 sets initial values that are not given from the prior (see rjags::jags.model(), argument initrep): for a bounded parameter, it takes the value with the highest prior density, for an unbounded parameter the mean of many draws from the prior. For some parameters of JointAI's models, these values are extreme, and the model cannot be initialised ("Node inconsistent with parents"):

Usage

add_jags5_inits(inits, nodes, seed, jags5 = rjags::jags.version() >= "5.0.0")

Arguments

inits

a list with one list of initial values per chain, as obtained from get_initial_values()

nodes

a named integer vector, as obtained from get_jags5_init_nodes(): per node the number of rows and columns of a precision matrix, or 0L for a single value

seed

an optional seed value, to draw the same values again

jags5

logical; whether the initial values are added (by default with JAGS >= 5)

Details

JAGS 4 started these models at values that worked (the random effects at zero, the shape at about 10), so nothing is changed for JAGS < 5.

The initial values are drawn per chain from a log-uniform distribution between 0.5 and 2 (so that the chains start at different values; for a precision, the variance then lies in the same range). Values the user supplied for a node are kept.

Value

inits, with an initial value for each node that is not in the initial values of a chain (see draw_jags5_init())


Add line breaks to a linear predictor string

Description

Adds line breaks to a string, breaking it after a "+" sign to not exceed a given width of characters and taking into account indentation.

Usage

add_linebreaks(string, indent, width = 90L)

Arguments

string

a character string (linear predictor)

indent

integer; number of characters the new line should be indented

width

integer; the maximum number of characters per line


Continue sampling from an object of class JointAI

Description

This function continues the sampling from the MCMC chains of an existing object of class 'JointAI'.

Usage

add_samples(object, n.iter, add = TRUE, thin = NULL,
  monitor_params = NULL, progress.bar = "text", mess = TRUE)

Arguments

object

object inheriting from class 'JointAI'

n.iter

the number of additional iterations of the MCMC chain

add

logical; should the new MCMC samples be added to the existing samples (TRUE; default) or replace them? If samples are added the arguments monitor_params and thin are ignored. If the object has no samples yet, the new samples are its samples.

thin

thinning interval (see window.mcmc); ignored when add = TRUE.

monitor_params

named list or vector specifying which parameters should be monitored. For details, see *_imp and the vignette Parameter Selection. Ignored when add = TRUE.

progress.bar

character string specifying the type of progress bar. Possible values are "text" (default), "gui", and "none" (see update). Note: when sampling is performed in parallel it is not possible to display a progress bar.

mess

logical; should messages be given? Default is TRUE.

Value

An object of class 'JointAI': object with the MCMC sample extended by the new iterations (add = TRUE) or replaced by them (add = FALSE), and with updated MCMC settings and computational time.

See Also

*_imp

The vignette Parameter Selection contains some examples on how to specify the argument monitor_params.

Examples

# Example 1:
# Run an initial JointAI model:
mod <- lm_imp(y ~ C1 + C2, data = wideDF, n.iter = 100)

# Continue sampling:
mod_add <- add_samples(mod, n.iter = 200, add = TRUE)


# Example 2:
# Continue sampling, but additionally sample imputed values.
# Note: Setting different parameters to monitor than in the original model
# requires add = FALSE.
imps <- add_samples(mod, n.iter = 200, monitor_params = c("imps" = TRUE),
                    add = FALSE)


Extract names of variables from several objects

Description

Version of all.vars() that can handle formulas, lists of formulas and character strings.

Usage

all_vars(...)

Arguments

...

formula objects, lists of formulas or character strings that are valid variable names (in the sense of make.vars())


Autocorrelation of MCMC samples

Description

This function obtains the autocorrelation of the MCMC samples in an JointAI object via coda::autocorr.diag(). autocorr_plot() visualizes the results using ggplot2.

Usage

auto_corr(object, lags = 0:30, by_chain = TRUE, outcome = NULL,
  start = NULL, end = NULL, thin = NULL)

auto_corr_plot(object, lags = 0:30, by_chain = TRUE, outcome = NULL,
  start = NULL, end = NULL, thin = NULL)

Arguments

object

an object of class JointAI

lags

a numeric vector indicating the lags to consider

by_chain

logical; should the autocorrelation be computed for each chain separately?

outcome

optional; vector identifying the sub-models whose parameters are included, either by their indices (in the order of the list of model formulas) or their names (LHS of the respective model formula as character string). If NULL (default), all monitored parameters are included. With parameters from several sub-models, the coefficients are named "outcome: variable", otherwise by the variable only.

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

Value

a matrix or a list of matrix objects if by_chain = TRUE, or a ggplot() object for autocorr_plot().

Examples

fit <- lm_imp(y ~ C1 + C2 + B2, data = wideDF, n.iter = 200)
auto_corr(fit)
auto_corr_plot(fit)


B-Spline Basis for Polynomial Splines

Description

This function just calls bs() from the splines package.

Usage

bs(x, df = NULL, knots = NULL, degree = 3, intercept = FALSE,
  Boundary.knots = range(x), warn.outside = TRUE)

Arguments

x

the predictor variable. Missing values are allowed.

df

degrees of freedom; one can specify df rather than knots; bs() then chooses df-degree (minus one if there is an intercept) knots at suitable quantiles of x (which will ignore missing values). The default, NULL, takes the number of inner knots as length(knots). If that is zero as per default, that corresponds to df = degree - intercept.

knots

the internal breakpoints that define the spline. The default is NULL, which results in a basis for ordinary polynomial regression. Typical values are the mean or median for one knot, quantiles for more knots. See also Boundary.knots.

degree

degree of the piecewise polynomial—default is 3 for cubic splines.

intercept

if TRUE, an intercept is included in the basis; default is FALSE.

Boundary.knots

boundary points at which to anchor the B-spline basis (default the range of the non-NA data). If both knots and Boundary.knots are supplied, the basis parameters do not depend on x. Data can extend beyond Boundary.knots.

warn.outside

logical indicating if a warning should be signalled in case some x values are outside the boundary knots.


Check the names in assoc_type

Description

The names in assoc_type have to be terms in the survival part of a joint model that have an association type, i.e., a time-varying covariate or a function of it. Anything else (which would otherwise be ignored) is an error. A function with several columns is one term, and an interaction has no name of its own: it uses the association types of its elements. With several survival outcomes, a name has to apply to one of them. Does nothing if the model has no survival part of a joint model.

Usage

check_assoc_type_names(assoc_type, info_list, Mlist)

Arguments

assoc_type

named vector of association types, as given by the user, or NULL

info_list

list of model information, from get_model_info()

Mlist

list of model information, as created by divide_matrices()

Value

NULL, invisibly; called for its error.


Check classes of all variables used in the model

Description

Runs a check that all variables that are used in the model are of a known class (numeric, ordered, factor, logical, integer) so that type-appropriate models can be specified. Note: This function does not check the type of grouping variables, which may be character strings.

Usage

check_classes(data, fixed = NULL, random = NULL, auxvars = NULL,
  timevar = NULL, mess = TRUE)

Arguments

data

a data.frame

fixed

a formula

random

a formula

auxvars

a one-sided formula

timevar

a character string (name of the time variable, used in joint models)

mess

logical, if TRUE messages are printed

Details

used in model_imp (2020-06-09)

Value

nothing, but throws an error if a variable is of an unknown class


Run all data related checks

Description

Wrapper function to check that

Usage

check_data(data, fixed, random, auxvars, timevar, mess, warn)

Arguments

data

a data.frame

fixed

a formula (or list of formulas)

random

a one-sided formula (or list of one-sided formulas)

auxvars

a one-sided formula

timevar

a character string (name of the time variable, used in joint models)

mess

logical, if TRUE messages are printed

warn

logical, if TRUE warnings are printed

Details

used in model_imp() (2025-09-04)

Value

the cleaned data.frame


Check that the names of dummy variables are unique

Description

The columns of the design matrix are identified by their names. A variable whose name is equal to the name of a dummy variable of a factor (e.g., a variable B11 and the dummy of level 1 of a factor B1), or two factors with dummy variables of the same name, would be merged into one column. This function stops with an informative error in that case (#75).

Usage

check_dummy_names(refs, varnames)

Arguments

refs

a list with the reference categories of the factors, as returned by get_refs(); the attribute "dummies" of each element holds the names of the dummy variables

varnames

a character vector with the names of all variables used in the model

Details

used in divide_matrices (2026-10-31)

Value

nothing, but throws an error if the name of a dummy variable is equal to the name of a variable or of another dummy variable


Check for duplicate grouping levels

Description

Used within get_groups().

Usage

check_duplicate_groupings(groups)

Arguments

groups

a list of integer "id" variables

Value

NULL; throws an error if duplicate grouping levels are found


Check that no outcome is used in more than one model formula

Description

A variable can only be the outcome of one model (JAGS needs a directed acyclic graph, and a copy of an outcome would count its information twice). Gives an error when

  1. two parametric survival outcomes (survreg) have the same survival times (competing risks are not supported),

  2. the same variable (time, event indicator or other outcome) is used on the left hand side of more than one model formula,

  3. two different outcomes (other than event indicators) have identical values, e.g., a copy of an outcome.

Usage

check_duplicate_outcomes(outcomes)

Arguments

outcomes

list produced by extract_outcome_data(); uses the elements outcomes (a named list of data.frames, one per model formula; for survival outcomes the columns are time and event indicator) and fixed (the formulas, with attribute "type")

Details

Event indicators are compared by name only, so that, e.g., two survival outcomes without censoring are possible.

Proportional hazards models (coxph, JM) may share the survival time: with time-varying covariates, several survival outcomes are only possible with the same time variable (reformat_longsurvdata() and get_data_list() expect one), and with mutually exclusive event types this gives a cause-specific hazards model. A shared time variable is counted only once in checks 2 and 3. To be revisited when competing risks are implemented (Surv() with an event indicator with more than two values).

Value

NULL (invisibly); called for the error.


Check whether fixed or formula contains a random effects specification

Description

Checks if the objects provided to the formula and fixed arguments contain a random effects specification. This function is used in random effects models. In case the combined fixed and random effects formula is part of the fixed element, it is moved into the formula element.

Usage

check_fixed_random(arglist)

Arguments

arglist

A list containing 'fixed', 'random', and 'formula' elements.

Value

The updated arglist.arglist


Ensure object is a (list of) formula(s)

Description

Check if an object is NULL, a formula, or a list of formulas and (optionally) convert it to a list of formulas. If the input is of unknown type or if it is a list that has entries that are neither formula nor NULL, an error is thrown.

Usage

check_formula_list(formula, convert = TRUE)

Arguments

formula

An object expected to be either a formula, a list of formulas, or NULL.

convert

Logical; if TRUE, a single formula is wrapped in a list.

Details

Internal function; used in many help functions, get_refs, *_imp, predict (2022-02-05)

Value

A named list of formula (and/or NULL) objects, or NULL. If convert is FALSE, a single formula is returned as-is.


Replace a full with a block-diagonal variance covariance matrix

Description

Check if a full random effects variance covariance matrix is specified for a single variable. In that case, it is identical to a block-diagonal matrix. Change the rd_vcov specification to blockdiag for clarity (because then the variable name is used in the name of b, D, invD, ...)

Usage

check_full_blockdiag(rd_vcov)

Arguments

rd_vcov

a valid random effects variance-covariance structure specification (i.e., checked using expand_rd_vcov_full())

Value

a valid random effects variance-covariance structure specification


Check if a grouping variable varies within another grouping variable

Description

Check if a grouping variable varies within another grouping variable

Usage

check_groups_vary_within_lvl(lvl, grouping_df)

Arguments

lvl

a vector defining a grouping level

grouping_df

a data.frame with where each column contains the grouping indices of a hierarchical level (as obtained by get_groups(...))

Value

a named logical vector indicating for each grouping variable (column of grouping_df) whether it varies within the grouping defined by lvl


Sub-models without regression coefficients

Description

The JAGS models of the types glm, glmm, mlogit and mlogitmm need at least one regression coefficient (the loop over the priors of the coefficients would otherwise run from Inf to -Inf). This is not the case for a model without an intercept and without covariates, e.g. y ~ 0 or y ~ 0 + (1 | id).

Usage

check_has_coefficients(parelmts, varname)

Arguments

parelmts

the parameter elements of the model (list per design matrix, as returned by get_parelmts()).

varname

name of the outcome of the model.

Details

Stops with an informative error if the model has no regression coefficients.

Value

NULL, invisibly; called for the error.


Functions of several variables in the survival part of a joint model

Description

In the time-varying part of the linear predictor of the survival part of a joint model, the value of a column is written in terms of one variable (see paste_linpred_jm()), which, for example, is replaced by its expected value for the association type "underl.value". A function of several variables (e.g., I(age * chol)) that is part of M_lvlone because at least one of the variables is time-varying is therefore not possible. Functions of several baseline variables are not concerned.

Usage

check_jm_function_terms(lp_cols, trafos)

Arguments

lp_cols

named integer vector: the columns of M_lvlone in the linear predictor of the survival model (names are the column names).

trafos

data.frame with information on the transformations, with the columns colname, fct and var (Mlist$fcts_all), or NULL.

Details

Stops with an informative error if there is such a term.

Value

NULL, invisibly; called for the error.


Check the specification of a joint model

Description

A joint model needs subjects with repeated measurements and something that changes over time in the survival part. This function

Usage

check_jm_specification(info_list, Mlist, warn = TRUE)

Arguments

info_list

list of model information, from get_model_info()

Mlist

list of model information, as created by divide_matrices()

warn

logical; should the warnings be given?

Value

NULL, invisibly; called for its errors and warnings.


Covariates in the survival part of a joint model

Description

In a joint model, the survival outcome is linked to the longitudinal outcomes through the covariates of the survival part. A survival part without covariates (e.g., Surv(time, status) ~ 1, also with random effects) is therefore not meaningful, and the model set-up would stop with an uninformative error.

Usage

check_jm_survival_covariates(formula)

Arguments

formula

a formula or a list of formulas, as given to JM_imp().

Details

Stops with an informative error if the fixed effects part of a survival formula has no covariates. Other formulas are not concerned.

Value

NULL, invisibly; called for the error.


Terms of only the time variable in the survival part of a joint model

Description

The baseline hazard of a joint model is a (spline) function of time, so that the effect of a term that involves nothing but the time variable (e.g., day, ns(day, df = 3), log(day + 1) or I(day^2)) cannot (or hardly) be distinguished from it. Interactions of the time variable with another variable (e.g., chol:day) describe an effect of that other variable that changes over time, and are not concerned.

Usage

check_jm_time_terms(fixed, timevar)

Arguments

fixed

the formula of the survival model.

timevar

name of the time variable.

Details

Stops with an informative error if there is such a term.

Value

NULL, invisibly; called for the error.


Model types of the time-varying covariates of a joint model

Description

The integral over the hazard in a joint model is approximated with Gauss-Kronrod quadrature. The models of the time-varying covariates that are needed for it are written once more for the quadrature points (gkmodel_in_jm()). This is only implemented for the model types glmm and clmm; for others (mlogitmm, i.e., unordered factors with more than two categories, also complete ones) the JAGS model could not be set up.

Usage

check_jm_tv_modeltypes(tv_info)

Arguments

tv_info

named list with the model information of the time-varying covariates (the element tv_vars of the model information of the survival part); each element has the element modeltype.

Details

Stops with an informative error if a time-varying covariate has another model type.

Value

NULL, invisibly; called for the error.


Interactions in the survival part of a joint model with unknown elements

Description

An interaction term is only recognised as such (in Mlist$interactions) when all its elements are columns of the design matrices. In the time-varying part of the linear predictor of the survival part of a joint model, the value of an interaction term is the product of its elements (see paste_jm_interaction()), so that an interaction with an element that is not a column is not possible. This happens

Usage

check_jm_unknown_interactions(lp_cols, interactions, design_cols, refs,
  timevar)

Arguments

lp_cols

named integer vector: the columns of M_lvlone in the linear predictor of the survival model (names are the column names).

interactions

list of interaction terms, as in Mlist$interactions (output of match_interaction()).

design_cols

character vector: the names of all columns of the design matrices.

refs

list of reference category information (Mlist$refs).

timevar

name of the time variable.

Details

Stops with an informative error if there is such an interaction.

Value

NULL, invisibly; called for the error.


Check that model types given by the user fit the level of their variables

Description

A variable below the highest level (it varies within the groups of a grouping level) needs a model with random effects, a variable on the highest level a model without random effects. With a type without random effects, the model of a variable below the highest level would lose the part of its linear predictor on the higher levels. Types that are not known here are left to the later checks.

Usage

check_model_type_level(models_user, var_ranks, max_rank)

Arguments

models_user

a named character vector with the model types given by the user (argument models)

var_ranks

a named numeric vector with the rank of the level of each variable (as in get_grouping_levels())

max_rank

the rank of the highest level

Details

used in get_models (2026-11-07)

Value

nothing, but throws an error if a model type does not fit the level of its variable


Check and normalise the specification of the parameters to monitor

Description

monitor_params may be a named list or a named vector. When logical values and parameter names are combined with c(), the logical values become character strings ("TRUE", "FALSE"), and a vector of parameter names in other is split into elements with the names other1, other2, ... (#114). This function converts both forms to the same named list, and stops with an informative error for names that are not parameter groups of get_params().

Usage

check_monitor_params(monitor_params, argname = "monitor_params")

Arguments

monitor_params

named list or vector specifying which parameters should be monitored (see model_imp()), or NULL; also the argument subset of the output functions

argname

character string; the name of the argument, used in the error messages ("monitor_params" or "subset")

Details

used in model_imp(), add_samples() and get_subset() (2026-11-06)

Value

a named list with one element per parameter group: TRUE or FALSE (or as given, e.g. NULL) for the parameter groups, and a character vector of parameter names for other


Check for missing values in grouping variables

Description

Checks if any grouping variable contains missing values (NA or NaN) and throws an error if so. Used within get_groups().

Usage

check_na_groupings(groups)

Arguments

groups

a list of integer "id" variables

Value

NULL; throws an error if missing values are found in any grouping variable


Outcomes that do not vary within the grouping of their random effects

Description

A model with random effects for a grouping variable needs an outcome that varies within the groups. An outcome that is constant within the groups (e.g., a variable on the level of the subjects with (1 | id)) has one value per group, and its random effects for this grouping cannot be estimated. Without this check, the JAGS model had an empty linear predictor (JAGS error) or, for multinomial mixed models, no covariates and no random effects at all.

Usage

check_outcome_varies_within_groups(fixed, random, data)

Arguments

fixed

named list of fixed effects formulas.

random

list of random effects formulas, with the same names as fixed (elements can be NULL).

data

the data.

Details

Survival outcomes are not checked: in survival models with time-varying covariates, the random-effects part specifies the subjects. Missing values of the outcome are ignored.

Value

NULL, invisibly; called for the error.


Check / create the random effects variance-covariance matrix specification

Description

Check / create the random effects variance-covariance matrix specification

Usage

check_rd_vcov(rd_vcov, nranef)

Arguments

rd_vcov

variance covariance specification provided by the user

nranef

list by level with named vectors of number of random effects per variable (obtained by get_nranef())


First validation for rd_vcov

Description

Checks if rd_vcov is a list with elements for all grouping levels or does not specify a grouping level. If valid, this function also make sure that rd_vcov is a list per grouping level by duplicating the contents if necessary.

Usage

check_rd_vcov_list(rd_vcov, idvar)

Arguments

rd_vcov

a character string or a list describing the the random effects variance covariance structure (provided by the user)

idvar

vector with the names of all grouping variables (except "lvlone")

Value

A named list per grouping level where each elements contains information on how the random effects variance-covariance matrices on that level are structured. Per level it can be either a character string (e.g. "full") or a list specifying structures per (groups) of variable(s) (e.g. list(full = c("a", "b"), indep = "c"))


Check for unnecessary grouping levels

Description

Used within get_groups().

Usage

check_redundant_lvls(groups, nrow_data)

Arguments

groups

a list of integer "id" variables

Value

NULL; throws an error if unnecessary grouping levels are found


Check that a survival outcome is right-censored

Description

Gives an error for any other type of Surv() outcome, because the models in JointAI assume right-censoring and use the first column of the survival object as the time and the second as the event indicator.

Usage

check_surv_type(lhs, data)

Arguments

lhs

character string; the left hand side of a model formula. Anything that is not a call to Surv() is ignored.

data

a data.frame; used to evaluate the argument type, in case it is not given as a character string.

Details

The type is derived from the call and not from attr(Surv(...), "type"): convert_variables() turns a binary event indicator into a factor, and with a factor Surv() ignores type and returns "mright" or "mcounting".

Value

NULL, invisibly; called for the error.

Note

Used in extract_outcome_data().


Check that all variables in formulas are in the data

Description

Check that all variables in formulas are in the data

Usage

check_vars_in_data(datanames, fixed = NULL, random = NULL,
  auxvars = NULL, timevar = NULL)

Arguments

datanames

a character vector (of all variable names in the data)

fixed

the fixed effects formula (or list of formulas)

random

the random effects formula (or list of formulas)

auxvars

one-sided formula of auxiliary variables

timevar

a character string (name of the time variable, used in joint models)

Value

nothing, but throws an error if a variable is missing


Choose default analysis model based on outcome and data level

Description

Choose default analysis model based on outcome and data level

Usage

choose_default_model(outcome, lvl, max_lvl)

Arguments

outcome

outcome variable

lvl

hierarchical level of the outcome variable

max_lvl

maximum hierarchical level in the data

Value

character string giving the default model type


Replace ":" with "_" in a string

Description

Cleans up factor levels (or other strings) by replacing ":" with "_" to avoid issues with the current implementation of identifying interactions (which looks for ":" in model terms).

Usage

clean_names(string)

Arguments

string

a character string

Details

used in this file (in convert_variables()) (2020-06-09)

Value

the cleaned character string


Convert a survival outcome to a model name

Description

A helper function that converts the "name of a survival model" (the "Surv(time, status)" specification) into a valid variable name so that it can be used in the JAGS model syntax.

Usage

clean_survname(x)

Arguments

x

a character string or vector of character strings

Value

A character vector of the same length as x, in which survival outcomes ("Surv(...)") are replaced by valid variable names; other values are returned unchanged.


Is a regression coefficient monitored?

Description

Is a regression coefficient monitored?

Usage

coef_is_monitored(coef, var_names)

Arguments

coef

name of the coefficient, e.g. "alpha[3]" (or "beta" for a single coefficient, as in coef_list).

var_names

character vector of the parameters (nodes) to monitor.

Value

TRUE if the coefficient is monitored, as the whole node (e.g. "alpha"), as element ("alpha[3]"), or as part of a range of elements ("alpha[2:4]").


The term in the model formula that a column of a design matrix belongs to

Description

A function with several columns (e.g., ns(chol, df = 2), with the columns ⁠ns(chol, df = 2)1⁠ and ⁠ns(chol, df = 2)2⁠) is one term. Any other column is its own term.

Usage

column_to_term(columns, trafos)

Arguments

columns

character vector of column names

trafos

data.frame with information on the transformations, with the columns colname and fct (Mlist$fcts_all), or NULL

Value

A character vector with the term of each column.


Combine fixed and random effects formulas

Description

A function to combine nlme-style fixed and random effects formulas into lme4 style formulas.

Usage

combine_formula_lists(fixed, random, warn = TRUE)

Arguments

fixed

a fixed effects formula or list of such formulas

random

a random effects formula (only RHS) or list of such formulas

warn

logical; should the warning(s) be printed

Details

Internal function. Lists of formulas can be named or unnamed. Uses combine_formulas().


Combine a fixed and random effects formula

Description

Combine a single fixed and random effects formula by pasting them together.

Usage

combine_formulas(fixed, random)

Arguments

fixed

fixed effects formula (two-sided formula object)

random

random effects formula (one-sided formula object)

Details

Internal function, used in combine_formula_lists().


Compare the structure of two data.frames

Description

Compare the structure of two data.frames

Usage

compare_data_structure(data1, data2)

Arguments

data1

a data.frame

data2

a data.frame

Value

nothing, but prints messages if the class of any variable changed or if the levels of any factor variable changed


Complete the monitored parameters for transforming coefficients back

Description

With scaled covariates, the coefficients are transformed back after sampling (rescale_coefs()). The intercept, the thresholds (ordinal models) and the coefficients of the baseline hazard (proportional hazards models) of a sub-model take the centring of all its covariates, and the coefficients of the variables in cross-level interactions are corrected with the coefficients of the interactions. Therefore, if a coefficient, a threshold or a coefficient of the baseline hazard of a sub-model is monitored, all regression coefficients of that sub-model are monitored (not those of other sub-models).

Usage

complete_coef_monitoring(var_names, info_list, mess = TRUE)

Arguments

var_names

character vector of the parameters (nodes) to monitor, as passed to JAGS (get_params()).

info_list

list with the model information of each sub-model (get_model_info()).

mess

logical; show a message about the added parameters?

Value

var_names with the parameters that need to be added.


Complete the monitored parameters for transforming random effects back

Description

With scaled covariates, the random effects and their covariance matrices are transformed back after sampling (rescale_ranefs()). This needs, per block of random effects (get_ranef_blocks()):

Usage

complete_ranef_monitoring(var_names, info_list, mess = TRUE)

Arguments

var_names

character vector of the parameters (nodes) to monitor, as passed to JAGS (get_params()).

info_list

list with the model information of each sub-model (get_model_info()).

mess

logical; show a message about the added parameters?

Details

Only these are added: if some random effects of a few groups are monitored (e.g. b_y_id[5,2]), only the rest of their rows is added (b_y_id[5,1:2]), not the random effects of all groups.

Value

var_names with the parameters that need to be added.


Convert labelled variables

Description

Variables of class "labelled" (Hmisc, haven < 2.0.0) or "haven_labelled" (haven >= 2.0.0), e.g., from data imported from SPSS, are converted:

Usage

convert_labelled(data, allvars, mess = TRUE, ref_data = NULL)

Arguments

data

a data.frame

allvars

vector of names of the variables used in the model

mess

logical, if TRUE a message lists the variables that were converted to factors

ref_data

optional data.frame with the reference factor levels

Details

The variable label (attribute "label") is kept. SPSS user-defined missing values (class "haven_labelled_spss") are not treated as missing.

When ref_data is given (e.g., the data of a fitted model, when data is new data for prediction), factors get the levels of the corresponding factor in ref_data, and values without such a level become NA (with a warning).

Value

the data.frame with the converted variables


Convert variables

Description

Cleans up the data by

Usage

convert_variables(data, allvars, mess = TRUE)

Arguments

data

a data.frame

allvars

a character vector of the relevant variables in data

mess

logical, if TRUE messages are printed

Details

used in model_imp (2025-09-07)

Value

the cleaned data.frame


Cross-correlation of MCMC samples

Description

These functions compute the cross-correlations of the MCMC samples in an JointAI object via coda::crosscorr() and plot them using either the corrplot package or coda::crosscorr.plot().

Usage

cross_corr(object, outcome = NULL, start = NULL, end = NULL,
  thin = NULL)

cross_corr_plot(object, outcome = NULL, start = NULL, end = NULL,
  thin = NULL, type = "corrplot")

Arguments

object

an object of class JointAI

outcome

optional; vector identifying the sub-models whose parameters are included, either by their indices (in the order of the list of model formulas) or their names (LHS of the respective model formula as character string). If NULL (default), all monitored parameters are included. With parameters from several sub-models, the coefficients are named "outcome: variable", otherwise by the variable only.

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

type

character; type of plot to be produced. Either "corrplot" (default) or "coda".

Value

a matrix (or a plot)

Examples

fit <- lm_imp(y ~ C1 + C2 + B2, data = wideDF, n.iter = 200)
cross_corr(fit)
cross_corr_plot(fit, type = "coda")

Get the default values for hyper-parameters

Description

This function returns a list of default values for the hyper-parameters.

Usage

default_hyperpars()

Details

norm: hyper-parameters for normal and log-normal models

mu_reg_norm mean in the priors for regression coefficients
tau_reg_norm precision in the priors for regression coefficients
shape_tau_norm shape parameter in Gamma prior for the precision of the (log-)normal distribution
rate_tau_norm rate parameter in Gamma prior for the precision of the (log-)normal distribution

gamma: hyper-parameters for Gamma models

mu_reg_gamma mean in the priors for regression coefficients
tau_reg_gamma precision in the priors for regression coefficients
shape_tau_gamma shape parameter in Gamma prior for the precision of the Gamma distribution
rate_tau_gamma rate parameter in Gamma prior for the precision of the Gamma distribution

beta: hyper-parameters for beta models

mu_reg_beta mean in the priors for regression coefficients
tau_reg_beta precision in the priors for regression coefficients
shape_tau_beta shape parameter in Gamma prior for the precision of the beta distribution
rate_tau_beta rate parameter in Gamma prior for precision of the of the beta distribution

binom: hyper-parameters for binomial models

mu_reg_binom mean in the priors for regression coefficients
tau_reg_binom precision in the priors for regression coefficients

poisson: hyper-parameters for poisson models

mu_reg_poisson mean in the priors for regression coefficients
tau_reg_poisson precision in the priors for regression coefficients

multinomial: hyper-parameters for multinomial models

mu_reg_multinomial mean in the priors for regression coefficients
tau_reg_multinomial precision in the priors for regression coefficients

ordinal: hyper-parameters for ordinal models

mu_reg_ordinal mean in the priors for regression coefficients
tau_reg_ordinal precision in the priors for regression coefficients
mu_delta_ordinal mean in the prior for the intercepts
tau_delta_ordinal precision in the priors for the intercepts

ranef: hyper-parameters for the random effects variance-covariance matrices (when there is only one random effect a Gamma distribution is used instead of the Wishart distribution)

shape_diag_RinvD shape parameter in Gamma prior for the diagonal elements of RinvD
rate_diag_RinvD rate parameter in Gamma prior for the diagonal elements of RinvD
KinvD_expr a character string that can be evaluated to calculate the number of degrees of freedom in the Wishart distribution used for the inverse of the variance-covariance matrix for random effects, depending on the number of random effects nranef

surv: parameters for survival models (survreg, coxph and JM)

mu_reg_surv mean in the priors for regression coefficients
tau_reg_surv precision in the priors for regression coefficients

Value

A named list with one named vector of hyper-parameters per type of model (the elements described above).

Note

From the JAGS user manual on the specification of the Wishart distribution:
For KinvD larger than the dimension of the variance-covariance matrix the prior on the correlation between the random effects is concentrated around 0, so that larger values of KinvD indicate stronger prior belief that the elements of the multivariate normal distribution are independent. For KinvD equal to the number of random effects the Wishart prior puts most weight on the extreme values (correlation 1 or -1).

Examples

default_hyperpars()

# To change the hyper-parameters:
hyp <- default_hyperpars()
hyp$norm['rate_tau_norm'] <- 1e-3
mod <- lm_imp(y ~ C1 + C2 + B1, data = wideDF, hyperpars = hyp, mess = FALSE)



Plot the posterior density from object of class JointAI

Description

The function plots a set of densities (per chain and coefficient) from the MCMC sample of an object of class "JointAI".

Usage

densplot(object, ...)

## S3 method for class 'JointAI'
densplot(object, start = NULL, end = NULL, thin = NULL,
  subset = c(analysis_main = TRUE), outcome = NULL,
  exclude_chains = NULL, vlines = NULL, nrow = NULL, ncol = NULL,
  joined = FALSE, use_ggplot = FALSE, warn = TRUE, mess = TRUE, ...)

Arguments

object

object inheriting from class 'JointAI'

...

additional parameters passed to plot()

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

subset

subset of parameters/variables/nodes (columns in the MCMC sample). Follows the same principle as the argument monitor_params in *_imp.

outcome

optional; vector identifying a subset of sub-models included in the output, either by specifying their indices (using the order used in the list of model formulas), or their names (LHS of the respective model formula as character string)

exclude_chains

optional vector of the index numbers of chains that should be excluded

vlines

list, where each element is a named list of parameters that can be passed to graphics::abline() to create vertical lines. Each of the list elements needs to contain at least v = <x location> where <x location> is a vector of the same length as the number of plots (see examples).

nrow

optional; number of rows in the plot layout; automatically chosen if unspecified

ncol

optional; number of columns in the plot layout; automatically chosen if unspecified

joined

logical; should the chains be combined before plotting?

use_ggplot

logical; Should ggplot be used instead of the base graphics?

warn

logical; should warnings be given? Default is TRUE.

mess

logical; should messages be given? Default is TRUE.

Value

With use_ggplot = TRUE (only for objects of class 'JointAI') a ggplot object. Otherwise, the plots are drawn with base graphics and NULL is returned invisibly.

See Also

The vignette Parameter Selection contains some examples how to specify the argument subset.

Examples


## Not run: 
# fit a JointAI object:
mod <- lm_imp(y ~ C1 + C2 + M1, data = wideDF, n.iter = 100)

# Example 1: basic densityplot
densplot(mod)
densplot(mod, exclude_chains = 2)


# Example 2: use vlines to mark zero
densplot(mod, col = c("darkred", "darkblue", "darkgreen"),
         vlines = list(list(v = rep(0, nrow(summary(mod)$res$y$regcoef)),
                            col = grey(0.8))))


# Example 3: use vlines to visualize posterior mean and 2.5%/97.5% quantiles
res <- rbind(summary(mod)$res$y$regcoef[, c('Mean', '2.5%', '97.5%')],
             summary(mod)$res$y$sigma[, c('Mean', '2.5%', '97.5%'),
             drop = FALSE]
             )
densplot(mod, vlines = list(list(v = res[, "Mean"], lty = 1, lwd = 2),
                            list(v = res[, "2.5%"], lty = 2),
                            list(v = res[, "97.5%"], lty = 2)))


# Example 4: ggplot version
densplot(mod, use_ggplot = TRUE)


# Example 5: change how the ggplot version looks
library(ggplot2)

densplot(mod, use_ggplot = TRUE) +
  xlab("value") +
  theme(legend.position = 'bottom') +
  scale_color_brewer(palette = 'Dark2', name = 'chain')

## End(Not run)


Converts a difftime object to a data.frame

Description

Converts a difftime object to a data.frame

Usage

difftime_df(dt)

Arguments

dt

difftime object (vector of difftime objects)


Draw an initial value for a node (JAGS >= 5)

Description

Draw an initial value for a node (JAGS >= 5)

Usage

draw_jags5_init(size)

Arguments

size

the number of rows and columns of a precision matrix, or 0L for a single value (see get_jags5_init_nodes())

Value

a single value, or, for size > 0, a matrix with the values on the diagonal and NA elsewhere (these elements are data or not used); the values are drawn from a log-uniform distribution between 0.5 and 2


Check for empty factor levels

Description

CHECKS if there are empty factor levels in any of the variables used in the model.

Usage

drop_levels(data, allvars, warn = TRUE, mess = NULL)

Arguments

data

a data.frame

allvars

a character vector (of all variable names used in the model)

warn

logical, if TRUE warnings are printed

Value

the data.frame (unchanged)

Note

Originally, the function also dropped these levels. Then, I (accidentally?) had commented out a line so that no check was performed. Now, only create a warning if there are empty levels, but do not drop them.

used in model_imp (2020-06-09)


Create a duration object

Description

Add row names to the object

Usage

duration_obj(dur)

Arguments

dur

list of difftime objects


Escape special characters for use in a regular expression

Description

Names of variables and parameters may contain characters with a special meaning in a regular expression, e.g., . in y.1 and [ in beta[1]. With this function they only match themselves.

Usage

escape_regex(x)

Arguments

x

character vector.

Value

x with a backslash before each special character.


Write out the elements of a range of elements

Description

Write out the elements of a range of elements

Usage

expand_element_names(element)

Arguments

element

a requested element or range of elements of a node, as given to JAGS (e.g., "b_y_id[5,1:2]")

Value

a character vector with one name per element, as JAGS names the columns of the samples, with the first index varying fastest (e.g., c("b_y_id[5,1]", "b_y_id[5,2]"))


Expand rd_vcov using variable names in case "full" is used

Description

Expand rd_vcov using variable names in case "full" is used

Usage

expand_rd_vcov_full(rd_vcov, rd_outnam)

Arguments

rd_vcov

the random effects variance covariance structure provided by the user (check_rd_vcov_list() is called internally)

rd_outnam

list by grouping level of the names of the outcome variables that have random effects on this level

Value

A named list per grouping level where each elements contains information on how the random effects variance-covariance matrices on that level are structured. Per level there is a list of grouping structures containing the names of variables in each structure (e.g. list(full = c("a", "b"), indep = "c"))


Extract fixed effects formula from lme4-type formula

Description

Extract fixed effects formula from lme4-type formula

Usage

extract_fixef_formula(formula)

Arguments

formula

a formula object (typically in lme4-style)

Value

a formula object


Extract grouping variables from a (list of) formula(s)

Description

Extracts the grouping variables (i.e., variables after |) from a model formula or a list of such formulas

Usage

extract_grouping(formula, warn = FALSE)

Arguments

formula

a formula object or a list of formula objects

warn

does nothing

Value

a vector of character strings containing the unique grouping variable names found in any of the input formulas, or NULL if there is no grouping found


Extract the left hand side of a formula

Description

Extracts the left hand side from a formula object and returns it as character string.

Usage

extract_lhs_string(formula)

Arguments

formula

a formula object (NOT a list of formulas)

Details

Internal; used in various help functions (2022-02-05)

Value

A character string.


Extract variable names from the left-hand side of a formula

Description

This internal helper function extracts variable names from the left-hand side (LHS) of a formula or a list of formulas. It supports standard formulas, survival objects, transformations (e.g., log(x)), and multivariate outcomes (e.g., cbind(a, b, c)).

Usage

extract_lhs_varnames(formula)

Arguments

formula

A formula object, a list of formulas, or NULL.

Value

A character vector of variable names from the LHS of the formula, or a list of such vectors if a list of formulas is provided. Returns NULL if the input is NULL.

See Also

extract_lhs_string()


Extract random effects formula from lme4-type formula

Description

Extract random effects formula from lme4-type formula

Usage

extract_ranef_formula(formula)

Arguments

formula

a formula object (typically in lme4-style)

Value

a one-sided formula object (or NULL if there are no random effects)


Return the current state of a 'JointAI' model

Description

Return the current state of a 'JointAI' model

Usage

extract_state(object, pattern = paste0("^", c("RinvD", "invD", "tau", "b"),
  "_"))

Arguments

object

an object of class 'JointAI'

pattern

vector of patterns to be matched with the names of the nodes

Value

A list with one element per chain of the MCMC sampler, containing the current state of the sampler (values of the last iteration) for the subset of nodes identified based on the pattern the user has specified.

Examples


mod <- lme_imp(y ~ C1 + time + (time | id), data = longDF, n.iter = 100,
               mess = FALSE)

# by default: the random effects and the (inverse) variance parameters
state <- extract_state(mod)
names(state[[1]])

# only the nodes whose name matches a pattern
extract_state(mod, pattern = "^tau_")



Convert a factor to an integer representation

Description

Convert a factor to an integer representation

Usage

factor_to_integer(x)

Arguments

x

a vector. If x is a factor it will be converted to integers as described below; otherwise x is returned unchanged.

Value

An integer vector when x is a factor, otherwise the original x.

Note

Used in extract_outcome_data().


Extract multiple imputed datasets from an object of class JointAI

Description

This function returns a dataset containing multiple imputed datasets stacked onto each other (i.e., long format; optionally including the original, incomplete data).
These data can be automatically exported to SPSS (as a .txt file containing the data and a .sps file containing syntax to generate a .sav file). For the export function the foreign package needs to be installed.

Usage

get_MIdat(object, m = 10, include = TRUE, start = NULL, minspace = 50,
  seed = NULL, export_to_SPSS = FALSE, resdir = NULL, filename = NULL)

Arguments

object

object inheriting from class 'JointAI'

m

number of imputed datasets

include

should the original, incomplete data be included? Default is TRUE.

start

the first iteration of interest (see window.mcmc)

minspace

minimum number of iterations between iterations to be chosen as imputed values (to prevent strong correlation between imputed datasets in the case of high autocorrelation of the MCMC chains).

seed

optional seed value

export_to_SPSS

logical; should the completed data be exported to SPSS?

resdir

optional; directory for results. If unspecified and export_to_SPSS = TRUE the current working directory is used.

filename

optional; file name (without ending). If unspecified and export_to_SPSS = TRUE a name is generated automatically.

Value

A data.frame in which the original data (if include = TRUE) and the imputed datasets are stacked onto each other.
The variable Imputation_ indexes the imputation, while .rownr links the rows to the rows of the original data. In cross-sectional datasets the variable .id is added as subject identifier.

Note

In order to be able to extract (multiple) imputed datasets the imputed values must have been monitored, i.e., imps = TRUE had to be specified in the argument monitor_params in *_imp.

See Also

plot_imp_distr

Examples


## Not run: 
# fit a model and monitor the imputed values with
# monitor_params = c(imps = TRUE)

mod <- lm_imp(y ~ C1 + C2 + M2, data = wideDF,
              monitor_params = c(imps = TRUE), n.iter = 100)

# Example 1: without export to SPSS
MIs <- get_MIdat(mod, m = 3, seed = 123)



# Example 2: with export for SPSS
# (here: to the temporary directory "temp_dir")

temp_dir <- tempdir()
MIs <- get_MIdat(mod, m = 3, seed = 123, resdir = temp_dir,
                 filename = "example_imputation",
                 export_to_SPSS = TRUE)


## End(Not run)


Re-create the full Mlist from a "JointAI" object

Description

Re-create the full Mlist from a "JointAI" object

Usage

get_Mlist(object)

Arguments

object

object of class "JointAI"


Time-varying covariates with an association type in a joint model

Description

Finds the columns of the linear predictor of the survival part of a joint model that need an association type, and the variable each of them belongs to.

Usage

get_assoc_covars(lp, Mlist, tvars)

Arguments

lp

list per design matrix with the columns of the linear predictor (named vectors of column numbers)

Mlist

list of model information, as created by divide_matrices(); used are interactions, refs and fcts_all

tvars

character vector with the names of the time-varying covariates

Details

Interaction terms are replaced by their elements, so that a covariate that is only part of an interaction also gets an association type. Dummy variables are replaced by their factor. A function of several variables (e.g., I(age * trig)) has one entry per variable, with the name of the column repeated, so that names and variables stay aligned; those that are not time-varying are then dropped.

Value

A character vector with the names of the variables, named by the column (for a factor: the name of the factor).


Parameters to include in the auto- and cross-correlation of MCMC samples

Description

Parameters to include in the auto- and cross-correlation of MCMC samples

Usage

get_corr_nodes(object, outcome)

Arguments

object

an object of class JointAI

outcome

optional; vector of indices or names of the sub-models whose parameters are selected; NULL selects all monitored parameters

Value

a character vector with the names of the selected columns of the MCMC sample, in the order of the MCMC sample


Determine grouping level of data

Description

For each column in a data.frame-like object, identify the hierarchical level as the highest grouping level from groups_df for which the column is identical for all members of every group.

Usage

get_datlvls(data, groups_df)

Arguments

data

a data.frame

groups_df

the data.frame of (integer) grouping vectors of length nrow(data).

Value

A named character vector of length ncol(data). Each element is the name of the grouping level at which the corresponding data column is constant.

See Also

get_grouping_levels


Identify the family from the covariate model type

Description

Identify the family from the covariate model type

Usage

get_family(model)

Arguments

model

character string; the covariate model type


Interactions to calculate at the quadrature points of a joint model

Description

In the survival part of a joint model, the models for the time-varying covariates are written again for the quadrature points, with the design matrix M_lvlonegk. In this matrix, the time-varying covariates (and the columns calculated from them) are missing (get_matgk()) and modelled or calculated in the JAGS model. This function selects the interaction terms that have to be calculated there: the interactions that are columns of M_lvlone, are used in the linear predictor of one of these models, and have an element that is (calculated from) a time-varying covariate modelled at the quadrature points. Their elements must be on the lowest level, or on the level of the survival outcome or above.

Usage

get_gk_interactions(tv_info, interactions, trafos, refs, surv_mat, group_lvls)

Arguments

tv_info

list with the model information of the time-varying covariates at the quadrature points (the element tv_vars of the model information of the survival part), named by the covariates.

interactions

list of interaction terms, as in Mlist$interactions (output of match_interaction()).

trafos

data frame with information on the functions of variables (Mlist$fcts_all).

refs

list with information on the reference categories of the factors (Mlist$refs).

surv_mat

name of the design matrix of the level of the survival outcome, e.g., "M_id".

group_lvls

named integer vector of the order of the grouping levels (Mlist$group_lvls).

Value

A (possibly empty) named list: the elements of interactions to be calculated at the quadrature points.


Get grouping levels

Description

A helper function that identifies the hierarchy of grouping variables. It checks for each grouping level how many of the other grouping levels it varies within and returns the ranked order of the grouping levels.

Usage

get_grouping_levels(grouping_df)

Arguments

grouping_df

a data.frame of grouping ("id") variables, as obtained from get_groups()

Value

a named integer vector identifying the grouping hierarchy, where "1" is the level of the individual observations and the largest number is the highest grouping level. Crossed levels will have the same number.


Get grouping information

Description

A helper function that generates grouping information from a data.frame and a character vector with the names of grouping variables. In all cases, the level "lvlone" is added to indicate the lowest level of the data (i.e., each observation is its own group).

Usage

get_groups(idvars, data)

Arguments

idvars

a character vector with the names of grouping variables

data

a data.frame

Value

a list with grouping information for each grouping level: each element is a vector of length nrow(data) with the group membership indices of each observation for the corresponding grouping level.


Get the nodes that get initial values from JointAI with JAGS >= 5

Description

Get the nodes that get initial values from JointAI with JAGS >= 5

Usage

get_jags5_init_nodes(info_list)

Arguments

info_list

a list with the information on the sub-models, as obtained from get_model_info()

Value

a named integer vector, as obtained from get_ranef_precision_nodes() and get_survreg_shape_nodes(): the number of rows and columns of a precision matrix, or 0L for a single value


Interactions in the time-varying part of the survival model of a joint model

Description

Selects the interaction terms among the time-varying columns of the linear predictor of the survival part of a joint model, and checks that all their elements are on the level of the time-varying covariates or on the level of the survival outcome.

Usage

get_jm_interactions(lp_cols, interactions, surv_mat)

Arguments

lp_cols

named integer vector: the columns of M_lvlone in the linear predictor of the survival model (names are the column names).

interactions

list of interaction terms, as in Mlist$interactions (output of match_interaction()).

surv_mat

name of the design matrix of the level of the survival outcome, e.g., "M_id".

Value

A (possibly empty) named list: the elements of interactions that are columns in lp_cols.


Get an element of a list, return a default value if it does not exist

Description

A small helper function to extract an element of a list and return a default value if the element does not exist (i.e., is NULL).

Usage

get_listelement(object, element, null_value = 0)

Arguments

object

a list

element

the name of the element to extract (a character string)

null_value

the value to return if the element does not exist

Value

the value of object[[element]] or null_value if object[[element]] is NULL


Obtain a summary of the missing values involved in an object of class JointAI

Description

This function returns the number and proportion of complete cases, and of missing values per variable, in the data used in the model, separately per level of the data.

Usage

get_missinfo(object)

Arguments

object

object inheriting from class JointAI

Value

A list with two elements:

complete_cases

a data.frame with one row per level and columns # (number of complete cases) and % (proportion of complete cases in percent);

miss_list

a list with one data.frame per level, with one row per variable and columns # NA (number of missing values) and % NA (proportion of missing values in percent).

In multi-level settings, the data.frames have an additional column level.

Examples

mod <-  lm_imp(y ~ C1 + B2 + C2, data = wideDF, n.iter = 100)
get_missinfo(mod)



Identify the general model type from the covariate model type

Description

Identify the general model type from the covariate model type

Usage

get_modeltype(model)

Arguments

model

character string; the covariate model type


Get the nodes that JAGS monitors

Description

Temporary, until rjags is fixed: rjags >= 5 (checked with rjags 5-5 and 5-6) cannot set a monitor on an element of a node whose name contains an underscore, letters and another underscore (e.g., D_y_id[1,2], the covariance matrix of the random effects of y on the level id); it warns "Failed to set value trace monitor". The cause is in parse.varnames() of rjags, which takes such names for reserved names (like "_observed_") and does not split them into node and index. The whole node can be monitored. With rjags >= 5, such elements are therefore replaced by their node, and select_monitored_columns() keeps the requested elements. Other names (e.g., beta, M_lvlone[3,2]) are monitored as they are. Monitoring whole nodes costs time for large nodes (e.g., the random effects of all subjects), so it is only done with rjags >= 5.

Usage

get_monitor_nodes(var_names,
  whole_nodes = numeric_version(getNamespaceVersion("rjags")) >= "5.0")

Arguments

var_names

a character vector with the names of the nodes and elements to monitor (e.g., "beta", "D_y_id[1,2]")

whole_nodes

logical; whether the affected elements are replaced by their node (by default with rjags >= 5)

Value

a character vector with the names to give to JAGS: var_names, with the affected elements replaced by the name of their node (each node once) if whole_nodes is TRUE, otherwise var_names


Get the node names of names of nodes and elements

Description

Get the node names of names of nodes and elements

Usage

get_node_name(x)

Arguments

x

a character vector with names of nodes or elements (e.g., "beta", "D_y_id[1,2]")

Value

a character vector with the names without the index (e.g., "beta", "D_y_id")


Extract the number of random effects

Description

This function extracts the number of random effects per variable and grouping level from the provided random effects formulas.

Usage

get_nranef(random, data)

Arguments

random

a random effect formula or list of random effects formulas

data

a data.frame

Value

a list of named vectors of the numbers of random effects per variable, were each list element refers to a (hierarchical) grouping level.


Random effects that share one covariance matrix

Description

Usually, each outcome has its own random effects per grouping level, ⁠b_<outcome>_<lvl>⁠, with covariance matrix ⁠D_<outcome>_<lvl>⁠. With rd_vcov = "full", the random effects of several outcomes form one vector ⁠b_<lvl>⁠ with covariance matrix ⁠D_<lvl>⁠; the attribute "ranef_index" of rd_vcov gives the positions of each outcome in it (e.g. "1:2").

Usage

get_ranef_blocks(info_list)

Arguments

info_list

list with the model information of each sub-model (get_model_info()).

Value

List with one element per covariance matrix: name (⁠b_<name>⁠, ⁠D_<name>⁠), lvl (grouping level), and parts, one per outcome, with info (model info), lvl_info (hierarchical-centring information of the level) and cols (positions of the outcome's random effects).


Get the precisions of random effects that have a truncated gamma prior

Description

The precision of a single random effect, and the precisions of independent random effects (rd_vcov = "indep"), have a truncated gamma prior (⁠dgamma(...)T(1e-16, 1e16)⁠, see rd_vcov_univ() and rd_vcov_indep()). Correlated random effects ("blockdiag", "full") have a Wishart prior; a "full" structure always has more than one random effect (with a single outcome it is "blockdiag").

Usage

get_ranef_precision_nodes(info_list)

Arguments

info_list

a list with the information on the sub-models, as obtained from get_model_info()

Value

a named integer vector: the number of random effects (the dimension of the precision matrix), named by the node of the precision matrix (e.g., c(invD_y_id = 1L)); of length zero if there are no such nodes


Identify the data matrix containing a given response variable

Description

Identify the data matrix containing a given response variable

Usage

get_resp_mat(resp, Mlvls, outnames)

Arguments

resp

character string; name of the response variable

Mlvls

named vector where the names are all column names of all data matrices, and the values are the names of the corresponding data matrices

outnames

character vector; names of the columns in the data matrices that contain the response variable (or multiple columns in case of a survival outcome)

Value

character string; the name(s) of the data matrix/matrices of the response variable(s)


Cross-level interactions in the means of random slopes

Description

With hierarchical centring, an interaction of a covariate w of a higher level with a random-slope variable z enters the mean of that random slope, so that the JAGS model contains beta * w * z with w and z scaled separately (not the scaled column w:z).

Usage

get_slope_interactions(info_list, data_list)

Arguments

info_list

list with the model info of each sub-model (uses the random-effects information in hc_list).

data_list

data list passed to JAGS (for the names of design-matrix columns).

Value

data.frame with one row per such term: outcome (name of the outcome as in coefs), term (column name of the interaction), w and z (column names of the two variables); no rows if there are none.


Get the shape parameters of Weibull survival models

Description

The shape parameter of a Weibull survival model (survreg_imp()) has the prior dexp(0.01) (see jagsmodel_survreg()).

Usage

get_survreg_shape_nodes(info_list)

Arguments

info_list

a list with the information on the sub-models, as obtained from get_model_info()

Value

a named integer vector with the value 0L (a single value, see add_jags5_inits()), named by the node of the shape parameter (e.g., c(shape_Srv_ftm_stts_cn = 0L)); of length zero if there are no survreg models


Columns that are scaled but must not be centred

Description

Centring a covariate moves part of its effect into a parameter that takes the role of an intercept: the intercept, the thresholds (ordinal models), the baseline hazard (proportional hazards models), or a random intercept. Where there is no such parameter, centring changes the model (#66). These columns are only scaled:

Usage

get_uncentred_columns(info_list, Mlist)

Arguments

info_list

list with the model information of each sub-model (get_model_info()).

Mlist

list of data matrices and related information (divide_matrices()).

Details

A column is used by all sub-models, so it is not centred if one of them needs this.

Value

Character vector of column names.


Values of a covariate for one group, per iteration

Description

Values of a covariate for one group, per iteration

Usage

group_covariate_values(cov_shift, g, lvl, groups, MCMC, data_list)

Arguments

cov_shift

element of the output of ranef_covariate_shift() (with matrix and col).

g

integer; the group (row of the random effects).

lvl

grouping level of the random effects.

groups

data.frame of grouping information (Mlist$groups; one row per row of the lowest level).

MCMC

MCMC sample (matrix); contains the imputed values of the covariate if they were monitored (columns ⁠<matrix>[<row>,<col>]⁠).

data_list

data list passed to JAGS.

Value

Vector with one value per iteration: the observed value, the imputed values, or NA if the value is missing and the imputed values were not monitored.


Get info on main effects in a rd slope structure for a level and sub-model

Description

Get info on main effects in a rd slope structure for a level and sub-model

Usage

hc_rdslope_info(hc_cols, parelmts)

Arguments

hc_cols

list of lists (one per random effect), each containing a list with elements "main" and "interact" that contain information on the column number and name of the design matrix for the random effects variables or variables interacting with them

parelmts

list (per design matrix) of indices of the regression coefficients used for that sub-model (named with the corresponding column name of the design matrix)

Details

Argument hc_cols should have the structure:

list(
  "(Intercept)" = list(main = c(M_id = 1),
                       interact = NULL),
  time = list(main = c(M_lvlone = 4),
              interact = list("C1:time" = list(interterm = c(M_lvlone = 6),
                                               elmts = c(M_id = 2,
                                                         M_lvlone = 4)),
                              "b21:time" = list(interterm = c(M_lvlone = 7),
                                                elmts = c(M_lvlone = 3,
                                                          M_lvlone = 4))
              )
  ),
  "I(time^2)" = list(main = c(M_lvlone = 5),
                     interact = NULL)
)

Argument parelmts is a list of lists instead of a list of vectors in case of a multinomial model or cumulative logit model with non-proportional effects.

Value

a data.frame with columns


Get info on the interactions with random slopes for a given level and sub-model

Description

Get info on the interactions with random slopes for a given level and sub-model

Usage

hc_rdslope_interact(hc_cols, parelmts, lvls)

Arguments

hc_cols

list of lists (one per random effect), each containing a list with elements "main" and "interact" that contain information on the column number and name of the design matrix for the random effects variables or variables interacting with them

parelmts

list (per design matrix) of indices of the regression coefficients used for that sub-model (named with the corresponding column name of the design matrix)

Details

Argument hc_cols should have the structure:

list(
  "(Intercept)" = list(main = c(M_id = 1),
                       interact = NULL),
  time = list(main = c(M_lvlone = 4),
              interact = list("C1:time" = list(interterm = c(M_lvlone = 6),
                                               elmts = c(M_id = 2,
                                                         M_lvlone = 4)),
                              "b21:time" = list(interterm = c(M_lvlone = 7),
                                                elmts = c(M_lvlone = 3,
                                                          M_lvlone = 4))
              )
  ),
  "I(time^2)" = list(main = c(M_lvlone = 5),
                     interact = NULL)
)

Argument parelmts is a list of lists instead of a list of vectors in case of a multinomial model or cumulative logit model with non-proportional effects.

Value

a data.frame with columns


Positions given as text

Description

Positions given as text

Usage

index_range(x)

Arguments

x

character string with one position (e.g. "3") or a range of positions (e.g. "1:2"), as in the attribute "ranef_index" of rd_vcov.

Value

Integer vector of the positions.


Convert a survival outcome to a model name

Description

A helper function that converts the "name of a survival model" (the "Surv(time, status)" specification) into a valid variable name so that it can be used in the JAGS model syntax.

Usage

internal_clean_survname(x)

Arguments

x

a character string or vector of character strings


Convert a variable with value labels to a factor

Description

Convert a variable with value labels to a factor

Usage

labelled_to_factor(x, levels = NULL)

Arguments

x

a labelled vector with attribute "labels" (a named vector of values)

levels

optional character vector of factor levels. If NULL, the levels are the (labels of the) observed values, sorted by value.

Value

an unordered factor with the value labels as levels, keeping the "label" attribute of x


List model details

Description

This function prints information on all models, those explicitly specified by the user and those specified automatically by JointAI for (incomplete) covariates in a JointAI object.

Usage

list_models(object, predvars = TRUE, regcoef = TRUE, otherpars = TRUE,
  priors = TRUE, refcat = TRUE)

Arguments

object

object inheriting from class 'JointAI'

predvars

logical; should information on the predictor variables be printed? (default is TRUE)

regcoef

logical; should information on the regression coefficients be printed? (default is TRUE)

otherpars

logical; should information on other parameters be printed? (default is TRUE)

priors

logical; should information on the priors (and hyper-parameters) be printed? (default is TRUE)

refcat

logical; should information on the reference category be printed? (default is TRUE)

Value

Called for its side effect: the information is printed and NULL is returned invisibly.

Note

The models listed by this function are not the actual imputation models, but the conditional models that are part of the specification of the joint distribution. Briefly, the joint distribution is specified as a sequence of conditional models

\[p(y | x_1, x_2, x_3, ..., \theta) p(x_1|x_2, x_3, ..., \theta) p(x_2|x_3, ..., \theta) ...\]

The actual imputation models are the full conditional distributions \(p(x_1 | \cdot)\) derived from this joint distribution. Even though the conditional distributions do not contain the outcome and all other covariates in their linear predictor, outcome and other covariates are taken into account implicitly, since imputations are sampled from the full conditional distributions. For more details, see Erler et al. (2016) and Erler et al. (2019).

The function list_models prints information on the conditional distributions of the covariates (since they are what is specified; the full-conditionals are automatically derived within JAGS). The outcome is, thus, not part of the printed linear predictor, but is still included during imputation.

References

Erler, N.S., Rizopoulos, D., Rosmalen, J.V., Jaddoe, V.W., Franco, O.H., & Lesaffre, E.M.E.H. (2016). Dealing with missing covariates in epidemiologic studies: A comparison between multiple imputation and a full Bayesian approach. Statistics in Medicine, 35(17), 2955-2974.

Erler NS, Rizopoulos D, Lesaffre EMEH (2021). "JointAI: Joint Analysis and Imputation of Incomplete Data in R." Journal of Statistical Software, 100(20), 1-56. doi:10.18637/jss.v100.i20.

Examples

# (set n.adapt = 0 and n.iter = 0 to prevent MCMC sampling to save time)
mod1 <- lm_imp(y ~ C1 + C2 + M2 + O2 + B2, data = wideDF, n.adapt = 0,
               n.iter = 0, mess = FALSE)

list_models(mod1)


Longitudinal example dataset

Description

A simulated longitudinal dataset.

Usage

data(longDF)

Format

A simulated data frame with 329 rows and 21 variables with data from 100 subjects:

C1

continuous, complete baseline variable

C2

continuous, incomplete baseline variable

B1

binary, complete baseline variable

B2

binary, incomplete baseline variable

M1

unordered factor; complete baseline variable

M2

unordered factor; incomplete baseline variable

O1

ordered factor; complete baseline variable

O2

ordered factor; incomplete baseline variable

P1

count variable; complete baseline variable

P2

count variable; incomplete baseline variable

c1

continuous, complete longitudinal variable

c2

continuous incomplete longitudinal variable

b1

binary, complete longitudinal variable

b2

binary incomplete longitudinal variable

o1

ordered factor; complete longitudinal variable

o2

ordered factor; incomplete longitudinal variable

p1

count variable; complete longitudinal variable

p2

count variable; incomplete longitudinal variable

id

id (grouping) variable

time

continuous complete longitudinal variable

y

continuous, longitudinal (outcome) variable


Monte Carlo error of each column of an MCMC sample

Description

Used by MC_error(), for the sample on the data scale and on the scale used in JAGS.

Usage

mce_matrix(mcmc, names, ...)

Arguments

mcmc

matrix of MCMC samples (all chains combined), one column per node.

names

character vector; names of the nodes (as printed), used as row names.

...

optional arguments passed to mcmcse::mcse().

Value

Matrix with one row per node and columns est (posterior mean), MCSE (Monte Carlo error), SD (posterior standard deviation) and MCSE/SD. If mcmcse::mcse() fails for a node, est and MCSE are NA.


Missing data pattern

Description

Obtain a plot of the pattern of missing data and/or return the pattern as a matrix.

Usage

md_pattern(data, color = c(grDevices::grey(0.1), grDevices::grey(0.7)),
  border = grDevices::grey(0.5), plot = TRUE, pattern = FALSE,
  print_xaxis = TRUE, ylab = "Number of observations per pattern",
  print_yaxis = TRUE, legend.position = "bottom", sort_columns = TRUE,
  ...)

Arguments

data

data frame

color

vector of length two, that specifies the colour used to indicate observed and missing values (in that order)

border

colour of the grid

plot

logical; should the missing data pattern be plotted? (default is TRUE)

pattern

logical; should the missing data pattern be returned as matrix? (default is FALSE)

print_xaxis, print_yaxis

logical; should the x-axis (below the plot) and y-axis (on the right) be printed?

ylab

y-axis label

legend.position

the default position of legends ("none", "left", "right", "bottom", "top", "inside")

sort_columns

logical; should the columns be sorted by number of missing values? (default is TRUE)

...

optional additional parameters, currently not used

Value

With plot = TRUE and pattern = FALSE (default) a ggplot object. With pattern = TRUE and plot = FALSE a matrix with one row per missing data pattern (1: observed, 0: missing), the column Npat (number of observations with this pattern), and the last row Nmis (number of missing values per variable, and in total). With both set to TRUE a list with elements plot and pattern; with both FALSE, NULL.

Note

This function requires the ggplot2 package to be installed.

See Also

See the vignette Visualizing Incomplete Data for more examples.

Examples

op <- par(mar = c(3, 1, 1.5, 1.5), mgp = c(2, 0.6, 0))
md_pattern(wideDF)
par(op)


Merge call arguments with default formals

Description

Merge call arguments with default formals

Usage

merge_call_args(formals, call, sframe)

Arguments

formals

List of formal arguments for ⁠*_imp()⁠.

call

The matched call from ⁠*_imp()⁠ as returned by match.call().

sframe

The environment within ⁠*_imp()⁠ (obtained from sys.frame(sys.nframe()))

Value

A list of arguments combining defaults and user-specified values.

Note

Helper function for prep_arglist.


Joint Analysis and Imputation of incomplete data

Description

Main analysis functions to estimate different types of models using MCMC sampling, while imputing missing values.

Usage

lm_imp(formula, data, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, models = NULL, no_model = NULL, shrinkage = FALSE,
  ppc = TRUE, seed = NULL, inits = NULL, warn = TRUE, mess = TRUE,
  ...)

glm_imp(formula, family, data, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, models = NULL, no_model = NULL, shrinkage = FALSE,
  ppc = TRUE, seed = NULL, inits = NULL, warn = TRUE, mess = TRUE,
  ...)

clm_imp(formula, data, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, nonprop = NULL, rev = NULL, models = NULL,
  no_model = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

lognorm_imp(formula, data, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, models = NULL, no_model = NULL, shrinkage = FALSE,
  ppc = TRUE, seed = NULL, inits = NULL, warn = TRUE, mess = TRUE,
  ...)

betareg_imp(formula, data, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, models = NULL, no_model = NULL, shrinkage = FALSE,
  ppc = TRUE, seed = NULL, inits = NULL, warn = TRUE, mess = TRUE,
  ...)

mlogit_imp(formula, data, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, models = NULL, no_model = NULL, shrinkage = FALSE,
  ppc = TRUE, seed = NULL, inits = NULL, warn = TRUE, mess = TRUE,
  ...)

lme_imp(fixed, data, random, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, rd_vcov = "blockdiag", models = NULL,
  no_model = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

lmer_imp(fixed, data, random, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, rd_vcov = "blockdiag", models = NULL,
  no_model = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

glme_imp(fixed, data, random, family, n.chains = 3, n.adapt = 100,
  n.iter = 0, thin = 1, monitor_params = c(analysis_main = TRUE),
  auxvars = NULL, refcats = NULL, rd_vcov = "blockdiag", models = NULL,
  no_model = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

glmer_imp(fixed, data, random, family, n.chains = 3, n.adapt = 100,
  n.iter = 0, thin = 1, monitor_params = c(analysis_main = TRUE),
  auxvars = NULL, refcats = NULL, rd_vcov = "blockdiag", models = NULL,
  no_model = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

betamm_imp(fixed, random, data, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, rd_vcov = "blockdiag", models = NULL,
  no_model = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

lognormmm_imp(fixed, random, data, n.chains = 3, n.adapt = 100,
  n.iter = 0, thin = 1, monitor_params = c(analysis_main = TRUE),
  auxvars = NULL, refcats = NULL, rd_vcov = "blockdiag", models = NULL,
  no_model = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

clmm_imp(fixed, data, random, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, nonprop = NULL, rev = NULL, rd_vcov = "blockdiag",
  models = NULL, no_model = NULL, shrinkage = FALSE, ppc = TRUE,
  seed = NULL, inits = NULL, warn = TRUE, mess = TRUE, ...)

mlogitmm_imp(fixed, data, random, n.chains = 3, n.adapt = 100,
  n.iter = 0, thin = 1, monitor_params = c(analysis_main = TRUE),
  auxvars = NULL, refcats = NULL, rd_vcov = "blockdiag", models = NULL,
  no_model = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

survreg_imp(formula, data, n.chains = 3, n.adapt = 100, n.iter = 0,
  thin = 1, monitor_params = c(analysis_main = TRUE), auxvars = NULL,
  refcats = NULL, models = NULL, no_model = NULL, shrinkage = FALSE,
  ppc = TRUE, seed = NULL, inits = NULL, warn = TRUE, mess = TRUE,
  ...)

coxph_imp(formula, data, df_basehaz = 6, n.chains = 3, n.adapt = 100,
  n.iter = 0, thin = 1, monitor_params = c(analysis_main = TRUE),
  auxvars = NULL, refcats = NULL, models = NULL, no_model = NULL,
  shrinkage = FALSE, ppc = TRUE, seed = NULL, inits = NULL,
  warn = TRUE, mess = TRUE, ...)

JM_imp(formula, data, df_basehaz = 6, n.chains = 3, n.adapt = 100,
  n.iter = 0, thin = 1, monitor_params = c(analysis_main = TRUE),
  auxvars = NULL, timevar = NULL, refcats = NULL,
  rd_vcov = "blockdiag", models = NULL, no_model = NULL,
  assoc_type = NULL, shrinkage = FALSE, ppc = TRUE, seed = NULL,
  inits = NULL, warn = TRUE, mess = TRUE, ...)

Arguments

formula

a two sided model formula (see formula) or a list of such formulas; (more details below).

data

a data.frame containing the original data (more details below)

n.chains

number of MCMC chains

n.adapt

number of iterations for adaptation of the MCMC samplers (see adapt)

n.iter

number of iterations of the MCMC chain (after adaptation; see coda.samples)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

monitor_params

named list or vector specifying which parameters should be monitored (more details below)

auxvars

optional; one-sided formula of variables that should be used as predictors in the imputation procedure (and will be imputed if necessary) but are not part of the analysis model(s). For more details with regards to the behaviour with non-linear effects see the vignette on Model Specification

refcats

optional; either one of "first", "last", "largest" (which sets the category for all categorical variables) or a named list specifying which category should be used as reference category per categorical variable. Options are the category label, the category number, or one of "first" (the first category), "last" (the last category) or "largest" (chooses the category with the most observations). Default is "first". If reference categories are specified for a subset of the categorical variables the default will be used for the remaining variables. (See also set_refcat)

models

optional; named vector specifying the types of models for (incomplete) covariates and for outcomes. This arguments replaces the argument meth used in earlier versions. If NULL (default) models will be determined automatically based on the class of the respective columns of data.

no_model

optional; vector of names of variables for which no model should be specified. Note that this is only possible for completely observed variables and implies the assumptions of independence between the excluded variable and the incomplete variables.

shrinkage

optional; either a character string naming the shrinkage method to be used for regression coefficients in all models or a named vector specifying the type of shrinkage to be used in the models given as names.

ppc

logical: should monitors for posterior predictive checks be set? (not yet used)

seed

optional; seed value (for reproducibility)

inits

optional; specification of initial values in the form of a list or a function (see jags.model). If omitted, starting values for the random number generator are created by JointAI, initial values are then generated by JAGS. With JAGS >= 5, JointAI draws initial values for the precisions of random effects that have a truncated gamma prior (a single random effect, or independent random effects) and for the shape parameter of Weibull survival models, if they are not given in inits. It is an error to supply an initial value for an observed node.

warn

logical; should warnings be given? Default is TRUE.

mess

logical; should messages be given? Default is TRUE.

...

additional, optional arguments

trunc

named list specifying limits of truncation for the distribution of the named incomplete variables (see the vignette ModelSpecification)

hyperpars

list of hyper-parameters, as obtained by default_hyperpars()

scale_vars

character vector with the names of the variables that will be centred and scaled (such that mean = 0 and sd = 1) when they enter a linear predictor to improve convergence of the MCMC sampling. By default, all numeric variables (including integer variables, e.g., counts) are scaled, as well as columns created by functions of numeric variables (e.g., ns(), log()) and interaction terms that involve a numeric variable. Factors are not scaled, and neither are numeric variables with only two distinct values, because these are converted to factors. If scale_vars is specified, only those of these that are named in it are scaled (for columns created by functions or interactions, the column name in the model matrix, e.g., "C1:C2"). TRUE is the same as the default; if set to FALSE no scaling will be done. Variables are only scaled, not centred, where centring would change the model because no intercept takes up the shift: in models without intercept, random-slope variables of a grouping level without random intercept, and variables in an interaction with a random-slope variable when the main effect of the other variable is not in the model.

custom

named list of JAGS model chunks (character strings) that replace the model for the given variable.

append_data_list

list that will be appended to the list containing the data that is passed to rjags (data_list). This may be necessary if additional data / variables are needed for custom (covariate) models. Note: since version 1.0.7 elements of append_data_list will overwrite existing elements of the data_list with the same name.

progress.bar

character string specifying the type of progress bar. Possible values are "text" (default), "gui", and "none" (see update). Note: when sampling is performed in parallel it is not possible to display a progress bar.

quiet

logical; if TRUE then messages generated by rjags during compilation as well as the progress bar for the adaptive phase will be suppressed, (see jags.model)

keep_scaled_mcmc

should the "original" MCMC sample (i.e., the scaled version returned by coda.samples()) be kept? (The MCMC sample that is re-scaled to the scale of the data is always kept.) Also applies to samples created with add_samples().

modelname

character string specifying the name of the model file (including the ending, either .R or .txt). If unspecified a random name will be generated.

modeldir

directory containing the model file or directory in which the model file should be written. If unspecified a temporary directory will be created.

overwrite

logical; whether an existing model file with the specified <modeldir>/<modelname> should be overwritten. If set to FALSE and a model already exists, that model will be used. If unspecified (NULL) and a file exists, the user is asked for input on how to proceed.

keep_model

logical; whether the created JAGS model file should be saved or removed from (FALSE; default) when the sampling has finished.

Other arguments are not used; their names are given in a warning (unless warn = FALSE).

family

only for glm_imp and glmm_imp/glmer_imp: a description of the distribution and link function to be used in the model. This can be a character string naming a family function, a family function or the result of a call to a family function. (For more details see below and family.) When formula is a list of formulas, family only applies to the first outcome; see the section on multiple models below.

nonprop

optional named list of one-sided formulas specifying covariates that have non-proportional effects in cumulative logit models. These covariates should also be part of the regular model formula, and the names of the list should be the names of the ordinal response variables.

rev

optional character vector; vector of ordinal outcome variable names for which the odds should be reversed, i.e., logit(y\le k) instead of logit(y > k).

fixed

a two sided formula describing the fixed-effects part of the model (see formula)

random

only for multi-level models: a one-sided formula of the form ~x1 + ... + xn | g, where x1 + ... + xn specifies the model for the random effects and g the grouping variable

rd_vcov

character string or list specifying the structure of the random effects variance covariance matrix, see details below.

df_basehaz

degrees of freedom for the B-spline used to model the baseline hazard in proportional hazards models (coxph_imp and JM_imp)

timevar

name of the variable indicating the time of the measurement of a time-varying covariate in a proportional hazards survival model (also in a joint model). The variable specified in "timevar" will automatically be added to "no_model".

assoc_type

named vector specifying the type of the association used for a time-varying covariate in the linear predictor of the survival model when using a "JM" model. Implemented options are "underl.value" (linear predictor; default for covariates modelled using a Gaussian, Gamma, beta or log-normal distribution) and "obs.value" (the observed/imputed value; default for covariates modelled using other distributions). The names are the terms of the survival model that should not use the default, as written in the formula, e.g., "chol" or "log(chol)"; other names give an error. An interaction uses the association types of its elements and has no name of its own.

Value

An object of class JointAI.

Model formulas

Random effects

It is possible to specify multi-level models as it is done in the package nlme, using fixed and random, or as it is done in the package lme4, using formula and specifying the random effects in brackets:

formula = y ~ x1 + x2 + x3 + (1 | id)

is equivalent to

fixed = y ~ x1 + x2 + x3, random = ~ 1|id

Multiple levels of grouping

For multiple levels of grouping the specification using formula should be used. There is no distinction between nested and crossed random effects, i.e., ... + (1 | id) + (1 | center) is treated the same as ... + (1 | center/id).

Nested vs crossed random effects

The distinction between nested and crossed random effects should come from the levels of the grouping variables, i.e., if id is nested in center, then there cannot be observations with the same id but different values for center.

Modelling multiple models simultaneously & joint models

To fit multiple main models at the same time, a list of formula objects can be passed to the argument formula. Outcomes of one model may be contained as covariates in another model and it is possible to combine models for variables on different levels, for example:

formula = list(y ~ x1 + x2 + x3 + x4 + time + (time | id),
                     x2 ~ x3 + x4 + x5)

This principle is also used for the specification of a joint model for longitudinal and survival data.

Note that it is not possible to specify multiple models for the same outcome variable.

The argument family only applies to the first outcome. The other outcomes get the default model for their variable type (see the section on model types below), e.g., a linear model for a numeric variable, also when family is poisson(). To use another model for these outcomes, specify it in the argument models, which also takes precedence over family for the first outcome, for example:

glm_imp(list(B1 ~ C1, B2 ~ C1), family = binomial("probit"), data = wideDF,
        models = c(B2 = "glm_binomial_probit"))
Random effects variance-covariance structure

(Note: This feature is new and has not been fully tested yet.)

By default, a block-diagonal structure is assumed for the variance-covariance matrices of the random effects in models with random effects. This means that per outcome and level random effects are assumed to be correlated, but random effects of different outcomes are modelled as independent. The argument rd_vcov allows the user specify different assumptions about these variance-covariance matrices. Implemented structures are full, blockdiag and indep (all off-diagonal elements are zero).

If rd_vcov is set to one of these options, the structure is assumed for the random effects of all outcomes that are specified in the model formula(s).

The structure only applies to these outcomes, i.e., the response variables in formula or fixed, or in a list of formulas for a multivariate model. The models for incomplete time-varying covariates that JointAI adds automatically always have their own (block-diagonal) variance-covariance matrix: their random effects are not correlated with those of the outcome(s), whatever is specified in rd_vcov. In a model with a single outcome, full and blockdiag are therefore the same, and indep means that the random effects of this outcome are independent of each other.

Alternatively, it is possible to specify a named list of vectors, where the names are the structures and the vectors contain the names of the response variables which are included in this structure.

For example, for a multivariate mixed model with five outcomes y1, ..., y5, the specification could be:

rd_vcov = list(blockdiag = c("y1", "y2"),
               full = c("y3", "y4"),
               indep = "y5")

This would entail that the random effects for y3 and y4 are assumed to be correlated (within and across outcomes), random effects for y1 and y2 are assumed to be correlated within each outcome, and the random effects for y5 are assumed to be independent.

It is possible to have multiple sets of response variables for which separate full variance-covariance matrices are used, for example:

rd_vcov = list(full = c("y1", "y2", "y5"),
               full = c("y3", "y4"))

In models with multiple levels of nesting, separate structures can be specified per level:

rd_vcov = list(id = list(blockdiag = c("y1", "y2"),
                         full = c("y3", "y4"),
                         indep = "y5"),
              center = "indep")

Survival models with frailties or time-varying covariates

Random effects specified in brackets can also be used to indicate a multi-level structure in survival models, as would, for instance be needed in a multi-centre setting, where patients are from multiple hospitals.

It also allows to model time-dependent covariates in a proportional hazards survival model (using coxph_imp), also in combination with additional grouping levels.

In time-dependent proportional hazards models, last-observation-carried-forward is used to fill in missing values in the time-varying covariates, and to determine the value of the covariate at the event time. Preferably, all time-varying covariates should be measured at baseline (timevar = 0). If a value for a time-varying covariate needs to be filled in and there is no previous observation, the next observation will be carried backward.

Differences to basic regression models

It is not possible to specify transformations of outcome variables, i.e., it is not possible to use a model formula like

log(y) ~ x1 + x2 + ...

In the specific case of a transformation with the natural logarithm, a log-normal model can be used instead of a normal model.

Moreover, it is not possible to use . to indicate that all variables in a data.frame other than the outcome variable should be used as covariates. I.e., a formula y ~ . is not valid in JointAI.

Data structure

For multi-level settings, the data must be in long format, so that repeated measurements are recorded in separate rows.

For survival data with time-varying covariates (coxph_imp and JM_imp) the data should also be in long format. The survival/censoring times and event indicator variables must be stored in separate variables in the same data and should be constant across all rows referring to the same subject.

During the pre-processing of the data the survival/censoring times will automatically be merged with the observation times of the time-varying covariates (which must be supplied via the argument timevar).

It is possible to have multiple time-varying covariates, which do not have to be measured at the same time points, but there can only be one timevar.

JM_imp needs a random effects structure that defines the subjects, and a time-varying term in the survival part or a longitudinal model; otherwise it gives an error (a proportional hazards model can be fitted with coxph_imp). The outcome of a sub-model that is neither in the survival part nor a covariate in another sub-model is assumed to be independent of the survival outcome, and there is a warning. There is also a warning for a time-varying covariate in the survival part without a model in the formula: its automatically added model only has a random intercept, which may not describe the change of the covariate over time well enough for a joint model.

Distribution families and link functions

gaussian with links: identity, log
binomial with links: logit, probit, log, cloglog
Gamma with links: inverse, identity, log
poisson with links: log, identity

Imputation methods / model types

Implemented model types that can be chosen in the argument models for baseline covariates (not repeatedly measured) are:

lm linear (normal) model with identity link (alternatively: glm_gaussian_identity); default for continuous variables
glm_gaussian_log linear (normal) model with log link
glm_gaussian_inverse linear (normal) model with inverse link
glm_logit logistic model for binary data (alternatively: glm_binomial_logit); default for binary variables
glm_probit probit model for binary data (alternatively: glm_binomial_probit)
glm_binomial_log binomial model with log link
glm_binomial_cloglog binomial model with complementary log-log link
glm_gamma_inverse gamma model with inverse link for skewed continuous data
glm_gamma_identity gamma model with identity link for skewed continuous data
glm_gamma_log gamma model with log link for skewed continuous data
glm_poisson_log Poisson model with log link for count data
glm_poisson_identity Poisson model with identity link for count data
lognorm log-normal model for skewed continuous data
beta beta model (with logit link) for skewed continuous data in (0, 1)
mlogit multinomial logit model for unordered categorical variables; default for unordered factors with >2 levels
clm cumulative logit model for ordered categorical variables; default for ordered factors

For repeatedly measured variables the following model types are available:

lmm linear (normal) mixed model with identity link (alternatively: glmm_gaussian_identity); default for continuous variables
glmm_gaussian_log linear (normal) mixed model with log link
glmm_gaussian_inverse linear (normal) mixed model with inverse link
glmm_logit logistic mixed model for binary data (alternatively: glmm_binomial_logit); default for binary variables
glmm_probit probit model for binary data (alternatively: glmm_binomial_probit)
glmm_binomial_log binomial mixed model with log link
glmm_binomial_cloglog binomial mixed model with complementary log-log link
glmm_gamma_inverse gamma mixed model with inverse link for skewed continuous data
glmm_gamma_identity gamma mixed model with identity link for skewed continuous data
glmm_gamma_log gamma mixed model with log link for skewed continuous data
glmm_poisson_log Poisson mixed model with log link for count data
glmm_poisson_identity Poisson mixed model with identity link for count data
glmm_lognorm log-normal mixed model for skewed covariates
glmm_beta beta mixed model for continuous data in (0, 1)
mlogitmm multinomial logit mixed model for unordered categorical variables; default for unordered factors with >2 levels
clmm cumulative logit mixed model for ordered factors; default for ordered factors

When models are specified for only a subset of the variables for which a model is needed, the default model choices (as indicated in the tables) are used for the unspecified variables.

Parameters to follow (monitor_params)

See also the vignette: Parameter Selection

Named vector specifying which parameters should be monitored. This can be done either directly by specifying the name of the parameter or indirectly by one of the key words selecting a set of parameters. Except for other, in which parameter names are specified directly, parameter (groups) are just set as TRUE or FALSE. When parameter groups and other are combined with c(), the logical values become character strings ("TRUE", "FALSE"), and several parameter names in other get the names other1, other2, ...; both are interpreted as intended.

Models are divided into two groups, the main models, which are the models for which the user has explicitly specified a formula (via formula or fixed), and all other models, for which models were specified automatically.

If left unspecified, monitor_params = c("analysis_main" = TRUE) will be used.

name/key word what is monitored
analysis_main betas and sigma_main, tau_main (for beta regression) or the shape parameter (for parametric survival models; it has no key word of its own, see below), gamma_main (for cumulative logit models), D_main (for multi-level models) and basehaz in proportional hazards models)
analysis_random ranef_main, D_main, invD_main, RinvD_main
other_models alphas, tau_other, gamma_other, delta_other
imps imputed values
betas regression coefficients of the main analysis model
tau_main precision of the residuals from the main analysis model(s)
sigma_main standard deviation of the residuals from the main analysis model(s)
gamma_main intercepts in ordinal main model(s)
delta_main increments of ordinal main model(s)
ranef_main random effects from the main analysis model(s) b
D_main covariance matrix of the random effects from the main model(s)
invD_main inverse(s) of D_main
RinvD_main matrices in the priors for invD_main
alphas regression coefficients in the covariate models
tau_other precision parameters of the residuals from covariate models
gamma_other intercepts in ordinal covariate models
delta_other increments of ordinal intercepts
ranef_other random effects from the other models b
D_other covariance matrix of the random effects from the other models
invD_other inverses of D_other
RinvD_other matrices in the priors for invD_other
other additional parameters

Shape parameter of parametric survival models:
The shape parameter of a parametric (Weibull) survival model (survreg_imp()) is monitored together with the other parameters of analysis_main. To monitor it without them, its name (e.g., shape_Surv_time_stats; shown by list_models()) can be given in other, e.g., monitor_params = list(analysis_main = FALSE, other = "shape_Surv_time_stats").

For example:
monitor_params = c(analysis_main = TRUE, tau_main = TRUE, sigma_main = FALSE) would monitor the regression parameters betas and the residual precision tau_main instead of the residual standard deviation sigma_main.

For a linear model, monitor_params = c(imps = TRUE) would monitor betas, and sigma_main (because analysis_main = TRUE by default) as well as the imputed values.

Scaled covariates:
When continuous covariates are scaled (see scale_vars), the parameters are transformed back to the scale of the original covariates after sampling. This requires some parameters to be monitored together, and these are added to the monitored parameters automatically (with a message):

To monitor exactly the specified parameters, the covariates can be left unscaled (scale_vars = FALSE); this may make the MCMC sampling less efficient.

Cumulative logit (mixed) models

In the default setting for cumulative logit models, i.e, rev = NULL, the odds for a variable \(y\) with \(K\) ordered categories are defined as \[\log\left(\frac{P(y_i > k)}{P(y_i \leq k)}\right) = \gamma_k + \eta_i, \quad k = 1, \ldots, K-1,\] where \(\gamma_k\) is a category specific intercept and \(\eta_i\) the subject specific linear predictor.

To reverse the odds to \[\log\left(\frac{P(y_i \leq k)}{P(y_i > k)}\right) = \gamma_k + \eta_i, \quad k = 1, \ldots, K-1,\] the name of the response variable has to be specified in the argument rev, e.g., rev = c("y").

By default, proportional odds are assumed and only the intercepts differ per category of the ordinal response. To allow for non-proportional odds, i.e., \[\log\left(\frac{P(y_i > k)}{P(y_i \leq k)}\right) = \gamma_k + \eta_i + \eta_{ki}, \quad k = 1, \ldots, K-1,\] the argument nonprop can be specified. It takes a one-sided formula or a list of one-sided formulas. When a single formula is supplied, or a unnamed list with just one element, it is assumed that the formula corresponds to the main model. To specify non-proportional effects for linear predictors in models for ordinal covariates, the list has to be named with the names of the ordinal response variables.

For example, the following three specifications are equivalent and assume a non-proportional effect of C1 on O1, but C1 is assumed to have a proportional effect on the incomplete ordinal covariate O2:

clm_imp(O1 ~ C1 + C2 + B2 + O2, data = wideDF, nonprop = ~ C1)
clm_imp(O1 ~ C1 + C2 + B2 + O2, data = wideDF, nonprop = list(~ C1))
clm_imp(O1 ~ C1 + C2 + B2 + O2, data = wideDF, nonprop = list(O1 = ~ C1))

To specify non-proportional effects on O2, a named list has to be provided:

clm_imp(O1 ~ C1 + C2 + B2 + O2 + B1, data = wideDF,
        nonprop = list(O1 = ~ C1,
                       O2 = ~ C1 + B1))

The variables for which a non-proportional effect is assumed also have to be part of the regular model formula.

Custom model parts

(Note: This feature is experimental and has not been fully tested yet.)

Via the argument custom it is possible to provide custom sub-models that replace the sub-models that are automatically generated by JointAI.

Using this feature it is, for instance, possible to use the value of a repeatedly measured variable at a specific time point as covariate in another model. An example would be the use of "baseline" cholesterol (chol at day = 0) as covariate in a survival model.

First, the variable chol0 is added to the PBC data. For most patients the value of cholesterol at baseline is observed, but not for all. It is important that the data has a row with day = 0 for each patient.

PBC <- merge(PBC,
             subset(PBC, day == 0, select = c("id", "chol")),
             by = "id", suffixes = c("", "0"))

Next, the custom piece of JAGS model syntax needs to be specified. We loop here only over the patients for which the baseline cholesterol is missing.

calc_chol0 <- "
for (ii in 1:28) {
  M_id[row_chol0_id[ii], 3] <- M_lvlone[row_chol0_lvlone[ii], 1]
  }"

To be able to run the model with the custom imputation "model" for baseline cholesterol we need to provide the numbers of the rows in the data matrices that contain the missing values of baseline cholesterol and the rows that contain the imputed cholesterol at day = 0:

row_chol0_lvlone <- which(PBC$day == 0 & is.na(PBC$chol0))
row_chol0_id <- match(PBC$id, unique(PBC$id))[row_chol0_lvlone]

Then we pass both the custom sub-model and the additional data to the analysis function coxph_imp(). Note that we explicitly need to specify the model for chol.

coxph_imp(list(Surv(futime, status != "censored") ~ age + sex + chol0,
               chol ~ age + sex + day + (day | id)),
          no_model = "day", data = PBC,
          append_data_list = list(row_chol0_lvlone = row_chol0_lvlone,
                                  row_chol0_id = row_chol0_id),
          custom = list(chol0 = calc_chol0))

Note

Coding of variables:

The default covariate (imputation) models are chosen based on the class of each of the variables, distinguishing between numeric, factor with two levels, unordered factor with >2 levels and ordered factor with >2 levels.

When a continuous variable has only two different values it is assumed to be binary and its coding and default (imputation) model will be changed accordingly. This behaviour can be overwritten specifying a model type via the argument models.

Variables of type logical are automatically converted to unordered factors.

Contrasts

JointAI version \(\geq\) 1.0.0 uses the globally (via options("contrasts")) specified contrasts. However, for incomplete categorical variables, for which the contrasts need to be re-calculated within the JAGS model, currently only contr.treatment and contr.sum are possible. Therefore, when an in complete ordinal covariate is used and the default contrasts (contr.poly()) are set to be used for ordered factors, a warning message is printed and dummy coding (contr.treatment()) is used for that variable instead.

Non-linear effects and transformation of variables:

JointAI handles non-linear effects, transformation of covariates and interactions the following way:
When, for instance, a model formula contains the function log(x) and x has missing values, x will be imputed and used in the linear predictor of models for which no formula was specified, i.e., it is assumed that the other variables have a linear association with x. The log() of the observed and imputed values of x is calculated and used in the linear predictor of the main analysis model.

If, instead of using log(x) in the model formula, a pre-calculated variable logx is used, this variable is imputed directly and used in the linear predictors of all models, implying that variables that have logx in their linear predictors have a linear association with logx but not with x.

When different transformations of the same incomplete variable are used in one model it is strongly discouraged to calculate these transformations beforehand and supply them as different variables. If, for example, a model formula contains both x and x2 (where x2 = x^2), they are treated as separate variables and imputed with separate models. Imputed values of x2 are thus not equal to the square of imputed values of x. Instead, x and I(x^2) should be used in the model formula. Then only x is imputed and x^2 is calculated from the imputed values of x internally.

The same applies to interactions involving incomplete variables.

Sequence of models:

Models generated automatically (i.e., not mentioned in formula or fixed are specified in a sequence based on the level of the outcome of the respective model in the multi-level hierarchy and within each level according to the number of missing values. This means that level-1 variables have all level-2, level-3, ... variables in their linear predictor, and variables on the highest level only have variables from the same level in their linear predictor. Within each level, the variable with the most missing values has the most variables in its linear predictor.

Not (yet) possible:

See Also

set_refcat, traceplot, densplot, summary.JointAI, MC_error, GR_crit, predict.JointAI, add_samples, JointAIObject, add_samples, parameters, list_models

Vignettes

Examples

# Example 1: Linear regression with incomplete covariates
mod1 <- lm_imp(y ~ C1 + C2 + M1 + B1, data = wideDF, n.iter = 100)


# Example 2: Logistic regression with incomplete covariates
mod2 <- glm_imp(B1 ~ C1 + C2 + M1, data = wideDF,
                family = binomial(link = "logit"), n.iter = 100)

## Not run: 

# Example 3: Linear mixed model with incomplete covariates
mod3 <- lme_imp(y ~ C1 + B2 + c1 + time, random = ~ time|id,
                data = longDF, n.iter = 300)


# Example 4: Parametric Weibull survival model
mod4 <- survreg_imp(Surv(time, status) ~ age + sex + meal.cal + wt.loss,
                    data = survival::lung, n.iter = 100)


# Example 5: Proportional hazards survival model
mod5 <- coxph_imp(Surv(time, status) ~ age + sex + meal.cal + wt.loss,
                    data = survival::lung, n.iter = 200)

# Example 6: Joint model for longitudinal and survival data
mod6 <- JM_imp(list(Surv(futime, status != 'censored') ~ age + sex +
                    albumin + copper + trig + (1 | id),
                    albumin ~ day + age + sex + (day | id)),
                    timevar = 'day', data = PBC, n.iter = 100)

# Example 7: Proportional hazards  model with a time-dependent covariate
mod7 <- coxph_imp(Surv(futime, status != 'censored') ~ age + sex + copper +
                  trig + stage + (1 | id),
                  timevar = 'day', data = PBC, n.iter = 100)



# Example 8: Parallel computation
# If no strategy how the "future" should be handled is specified, the
# MCMC chains are run sequentially.
# To run MCMC chains in parallel, a strategy can be specified using the
# package \pkg{future} (see ?future::plan), for example:
future::plan(future::multisession, workers = 4)
mod8 <- lm_imp(y ~ C1 + C2 + B2, data = wideDF, n.iter = 500, n.chains = 8)
mod8$comp_info$future
# To re-set the strategy to sequential computation, the sequential strategy
# can be specified:
future::plan(future::sequential)


## End(Not run)


Normalize formula arguments in arglist

Description

Normalize formula arguments in arglist

Usage

normalize_formula_args(arglist)

Arguments

arglist

A list containing at least formula, fixed, and random elements.

Value

The updated arglist with formulas converted to lists.

Note

Helper function used in prep_arglist().


Generate a Basis Matrix for Natural Cubic Splines

Description

This function just calls ns() from the splines package.

Usage

ns(x, df = NULL, knots = NULL, intercept = FALSE,
  Boundary.knots = range(x))

Arguments

x

the predictor variable. Missing values are allowed.

df

degrees of freedom. One can supply df rather than knots; ns() then chooses df - 1 - intercept knots at suitably chosen quantiles of x (which will ignore missing values). The default, df = NULL, sets the number of inner knots as length(knots).

knots

breakpoints that define the spline. The default is no knots; together with the natural boundary conditions this results in a basis for linear regression on x. Typical values are the mean or median for one knot, quantiles for more knots. See also Boundary.knots.

intercept

if TRUE, an intercept is included in the basis; default is FALSE.

Boundary.knots

boundary points at which to impose the natural boundary conditions and anchor the B-spline basis (default the range of the data). If both knots and Boundary.knots are supplied, the basis parameters do not depend on x. Data can extend beyond Boundary.knots


Names of the elements of a parameter vector in the MCMC sample

Description

JAGS names the elements name[1], name[2], ..., but a vector of length 1 just name.

Usage

par_names(name, n)

Arguments

name

character string; name of the parameter vector

n

integer; length of the parameter vector

Value

Character vector of length n with the names of the elements.


Parts of the names of parameters in the MCMC sample

Description

A parameter is the whole node ("alpha"), or one or more of its elements: "alpha[3]", "alpha[2:4]", "b_y_id[5,1:2]".

Usage

par_node(x)

par_index_text(x)

is_node_element(x, node)

Arguments

x

character vector of parameter names.

node

character string; name of the node.

Value

par_node(): character vector, x up to the first "[". par_index_text(): character vector, the text between the first "[" and the last "]"; a name without index is returned unchanged. is_node_element(): logical vector.


Parameter names of an JointAI object

Description

Returns the names of the parameters/nodes of an object of class 'JointAI' for which a monitor is set.

Usage

parameters(object, expand_ranef = FALSE, mess = TRUE, warn = TRUE, ...)

Arguments

object

object inheriting from class 'JointAI'

expand_ranef

logical; should all elements of the random effects vectors/matrices be shown separately?

mess

logical; should messages be given? Default is TRUE.

warn

logical; should warnings be given? Default is TRUE.

...

currently not used

Value

A data.frame with one row per monitored node and columns outcome (the outcome of the sub-model the parameter belongs to), outcat (the outcome category, for multinomial models and non-proportional effects in ordinal models; otherwise NA), varname (for regression coefficients: the name of the corresponding covariate or design matrix column) and coef (the name of the node in the JAGS model). For nodes that do not belong to a sub-model, e.g., imputed values, outcome, outcat and varname are NA.

Examples

# (This function does not need MCMC samples to work, so we will set
# n.adapt = 0 and n.iter = 0 to reduce computational time)
mod1 <- lm_imp(y ~ C1 + C2 + M2 + O2 + B2, data = wideDF, n.adapt = 0,
               n.iter = 0, mess = FALSE)

parameters(mod1)


Paste analysis type with family information

Description

Paste analysis type with family information

Usage

paste_analysis_type(analysis_type)

Arguments

analysis_type

character string, as created by the separate '*-imp()“ functions

Value

character string with family and link information appended


Write the coefficient part of a linear predictor

Description

Write the coefficient part of a linear predictor

Usage

paste_coef(parname, parelmts)

Arguments

parname

character string; name of the coefficient (e.g., "beta")

parelmts

vector of integers; the index of the parameter vector

Value

A vector of character strings of the form beta[3].


Write the data element of a linear predictor

Description

Write the data element of a linear predictor

Usage

paste_data(matnam, index, col, isgk = FALSE)

Arguments

matnam

characters string; name of the data matrix

index

character string; the index (e.g., "i", or "ii")

col

integer vector; the indices of the columns in matnam

isgk

logical; is this for within the Gauss-Kronrod quadrature?

Value

A vector of character strings of the form M_id[i, 3] or M_id[i, 3, k].


Write the interaction terms at the quadrature points of a joint model

Description

Writes the JAGS syntax that calculates the interaction terms selected by get_gk_interactions() in the design matrix at the quadrature points (M_lvlonegk), as the product of their elements, for each quadrature point. Elements in M_lvlone are taken from M_lvlonegk; elements on the level of the survival outcome or above from their design matrix, for the current unit of the survival outcome. Used in jagsmodel_jm(), inside the loop over the units of the survival outcome.

Usage

paste_gk_interactions(interactions, index, surv_lvl)

Arguments

interactions

named list of interaction terms (the element gk_interactions of the model information of the survival part).

index

character string; the index of the level of the survival outcome, e.g., "ii".

surv_lvl

character string; the level of the survival outcome, e.g., "id".

Value

A character string with the JAGS syntax, or NULL if there are no interaction terms.


Write a linear predictor

Description

Construct a linear predictor from parameter names and indices, the name of the data matrix and corresponding columns, and apply scaling to the data if necessary.

Usage

paste_linpred(parname, parelmts, matnam, index, cols, scale_pars,
  isgk = FALSE)

Arguments

parname

character string; name fo the parameter (e.g., "beta")

parelmts

integer vector; indices of the parameter vector to be used; should have the same length as cols

matnam

character string; name of the data matrix

index

character string; name of the index (e.g., "i" or "ii")

cols

integer vector; indices of the columns of matname, should have the same length as parlemts

scale_pars

matrix with row names according to the column names of matname and columns "center" and "scale"; or NULL

isgk

logical; is this linear predictor within the Gauss-Kronrod quadrature?


Create the scaling in a data element of a linear predictor

Description

Create the scaling in a data element of a linear predictor

Usage

paste_scale(x, row, scalemat)

Arguments

x

a character string

row

integer; indicating the row of scalemat to be used

scalemat

character string; name of the matrix containing the scaling information (e.g., "spM_lvlone"). This matrix is assumed to have columns "center" and "scale".

Value

a character string of the form (x - center)/scale.


Wrap a data element of a linear predictor in scaling syntax

Description

Identifies if a data element of a linear predictor should be scaled (based on whether scaling parameters are given) and then calls paste_scale().

Usage

paste_scaling(x, rows, scale_pars, scalemat)

Arguments

x

vector of character strings; to be scaled, typically matrix columns

rows

integer vector; row numbers of the matrix containing the scaling information

scale_pars

matrix containing the scaling information, with columns "center" and "scale"

scalemat

the name of the scaling matrix in the JAGS model (e.g. "spM_id")

Details

Calls paste_scale() on each element of x.


Plot an object object inheriting from class 'JointAI'

Description

Plot an object object inheriting from class 'JointAI'

Usage

## S3 method for class 'JointAI'
plot(x, ...)

Arguments

x

object inheriting from class 'JointAI'

...

currently not used

Value

Called for its side effect: a plot of the residuals against the fitted values is drawn and NULL is returned invisibly.

Note

Currently, plot() can only be used with (generalized) linear (mixed) models.

Examples

mod <- lm_imp(y ~ C1 + C2 + B1, data = wideDF, n.iter = 100)
plot(mod)


Visualize the distribution of all variables in the dataset

Description

This function plots a grid of histograms (for continuous variables) and bar plots (for categorical variables) and labels it with the proportion of missing values in each variable.

Usage

plot_all(data, nrow = NULL, ncol = NULL, fill = grDevices::grey(0.8),
  border = "black", allNA = FALSE, idvars = NULL, xlab = "",
  ylab = "frequency", ...)

Arguments

data

a data.frame (or a matrix)

nrow

optional; number of rows in the plot layout; automatically chosen if unspecified

ncol

optional; number of columns in the plot layout; automatically chosen if unspecified

fill

colour the histograms and bars are filled with

border

colour of the borders of the histograms and bars

allNA

logical; if FALSE (default) the proportion of missing values is only given for variables that have missing values, if TRUE it is given for all variables

idvars

name of the column that specifies the multi-level grouping structure

xlab, ylab

labels for the x- and y-axis

...

additional parameters passed to barplot and hist

Value

Called for its side effect: the plots are drawn with base graphics and NULL is returned invisibly.

See Also

Vignette: Visualizing Incomplete Data

Examples

op <- par(mar = c(2,2,3,1), mgp = c(2, 0.6, 0))
plot_all(wideDF)
par(op)


Plot the distribution of observed and imputed values

Description

Plots densities and bar plots of the observed and imputed values in a long-format dataset (multiple imputed datasets stacked onto each other).

Usage

plot_imp_distr(data, imp = "Imputation_", id = ".id", rownr = ".rownr",
  ncol = NULL, nrow = NULL, labeller = NULL)

Arguments

data

a data.frame containing multiple imputations and the original incomplete data stacked onto each other

imp

the name of the variable specifying the imputation indicator

id

the name of the variable specifying the subject indicator

rownr

the name of a variable identifying which rows correspond to the same observation in the original (un-imputed) data

ncol

optional; number of columns in the plot layout; automatically chosen if unspecified

nrow

optional; number of rows in the plot layout; automatically chosen if unspecified

labeller

optional labeller to be passed to ggplot2::facet_wrap() to change the facet labels

Value

A ggplot object combining the plots of all variables with imputed values (created with ggpubr::ggarrange()), or NULL (with a message) when the packages ggplot2 or ggpubr are not installed.

Examples


## Not run: 
mod <- lme_imp(y ~ C1 + c2 + B2 + C2, random = ~ 1 | id, data = longDF,
               n.iter = 200, monitor_params = c(imps = TRUE), mess = FALSE)
impDF <- get_MIdat(mod, m = 5)
plot_imp_distr(impDF, id = "id", ncol = 3)

## End(Not run)

Create a new data frame for prediction

Description

Build a data.frame for prediction, where one variable varies and all other variables are set to the reference value (median for continuous variables).

Usage

predDF(object, ...)

## S3 method for class 'JointAI'
predDF(object, vars, length = 100L, ...)

## S3 method for class 'formula'
predDF(object, data, vars, length = 100L, ...)

## S3 method for class 'list'
predDF(object, data, vars, length = 100L, idvar = NULL, ...)

Arguments

object

object inheriting from class 'JointAI'

...

optional specification of the values used for some (or all) of the variables given in vars

vars

name of variable that should be varying

length

number of values used in the sequence when vars is continuous

data

a data.frame containing the original data (more details below)

idvar

optional name of an ID variable

See Also

predict.JointAI, lme_imp, glm_imp, lm_imp

Examples

# fit a JointAI model (predDF() only uses the model specification and the
# data, so no MCMC sample is needed here)
mod <- lm_imp(y ~ C1 + C2 + M2, data = wideDF, n.adapt = 0, n.iter = 0)

# generate a data frame with varying "C2" and reference values for all other
# variables in the model
newDF <- predDF(mod, vars = ~ C2)

head(newDF)


newDF2 <- predDF(mod, vars = ~ C2 + M2,
                 C2 = seq(-0.5, 0.5, 0.25),
                 M2 = levels(wideDF$M2)[2:3])
newDF2


Predict values from an object of class JointAI

Description

Obtains predictions and corresponding credible intervals from an object of class 'JointAI'.

Usage

## S3 method for class 'JointAI'
predict(object, outcome = 1L, newdata,
  quantiles = c(0.025, 0.975), type = "lp", start = NULL, end = NULL,
  thin = NULL, exclude_chains = NULL, mess = TRUE, warn = TRUE,
  return_sample = FALSE, ...)

Arguments

object

object inheriting from class 'JointAI'

outcome

vector of variable names or integers identifying for which outcome(s) the prediction should be performed.

newdata

optional new dataset for prediction. If left empty, the original data is used.

quantiles

quantiles of the predicted distribution of the outcome

type

the type of prediction. The default is on the scale of the linear predictor ("link" or "lp"). Additionally, for generalized linear (mixed) models (incl. beta and log-normal) type = "response" transforms the predicted values to the scale of the response, and for ordinal and multinomial (mixed) models type may be "prob" (to obtain probabilities per class), "class" to obtain the class with the highest posterior probability, or "lp". For parametric survival models type can be "lp" or "response", and for proportional hazards survival models the options are "lp", "risk" (= exp(lp)), "survival" or "expected" (= -log(survival)). When the prediction is done for several outcomes, one value applies to all outcomes, and a named vector sets the type per outcome (outcomes that are not named get "lp").

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

exclude_chains

optional vector of the index numbers of chains that should be excluded

mess

logical; should messages be given? Default is TRUE.

warn

logical; should warnings be given? Default is TRUE.

return_sample

logical; should the full sample on which the summary (mean and quantiles) is calculated be returned?#'

...

currently not used

Details

A model.matrix X is created from the model formula (currently fixed effects only) and newdata. X\beta is then calculated for each iteration of the MCMC sample in object, i.e., X\beta has n.iter rows and nrow(newdata) columns. A subset of the MCMC sample can be selected using start, end and thin.

Value

A list with entries newdata, fitted and, if return_sample = TRUE, sample: fitted contains the predicted values (column fit; the mean over the values calculated from the iterations of the MCMC sample) and the specified quantiles (by default 2.5% and 97.5%), newdata is newdata, extended with these columns, and sample contains the predicted values for each iteration of the MCMC sample (in long format). For ordinal and multinomial models with type = "prob", fitted is a three-dimensional array (observations, mean and quantiles, categories). When the prediction is done for several outcomes, fitted and sample are lists with one element per outcome.

Note

Functionality will be extended in the future.

See Also

predDF.JointAI, *_imp

Examples

# fit model
mod <- lm_imp(y ~ C1 + C2 + I(C2^2), data = wideDF, n.iter = 100)

# calculate the fitted values
fit <- predict(mod)

# create dataset for prediction
newDF <- predDF(mod, vars = ~ C2)

# obtain predicted values
pred <- predict(mod, newdata = newDF)

# plot predicted values and 95% confidence band
matplot(newDF$C2, pred$fitted, lty = c(1, 2, 2), type = "l", col = 1,
xlab = 'C2', ylab = 'predicted values')


Prepare list of arguments for model_imp()

Description

Prepare list of arguments for model_imp()

Usage

prep_arglist(analysis_type, family = NULL, formals = formals(),
  call = match.call(), sframe = sys.frame(sys.nframe()))

Arguments

analysis_type

Type of analysis to be performed (from ⁠*_imp()⁠)

family

family object or character string specifying the error distribution and link function.

formals

List of formal arguments for the function.

call

The matched call as returned by match.call().

sframe

An environment (typically from sys.frame(sys.nframe()))

Value

A list of arguments prepared for model_imp(), including the analysis type, family, formulas, and other relevant parameters.


Summarize the results from an object of class JointAI

Description

Obtain and print the summary, (fixed effects) coefficients (coef) and credible interval (confint) for an object of class 'JointAI'.

Usage

## S3 method for class 'Dmat'
print(x, digits = getOption("digits"),
  scientific = getOption("scipen"), ...)

## S3 method for class 'JointAI'
summary(object, start = NULL, end = NULL, thin = NULL,
  quantiles = c(0.025, 0.975), subset = NULL, exclude_chains = NULL,
  outcome = NULL, missinfo = FALSE, warn = TRUE, mess = TRUE, ...)

## S3 method for class 'summary.JointAI'
print(x, digits = max(3, .Options$digits - 4), ...)

## S3 method for class 'JointAI'
coef(object, start = NULL, end = NULL, thin = NULL,
  subset = NULL, exclude_chains = NULL, warn = TRUE, mess = TRUE, ...)

## S3 method for class 'JointAI'
confint(object, parm = NULL, level = 0.95,
  quantiles = NULL, start = NULL, end = NULL, thin = NULL,
  subset = NULL, exclude_chains = NULL, warn = TRUE, mess = TRUE, ...)

## S3 method for class 'JointAI'
print(x, digits = max(4, getOption("digits") - 4), ...)

Arguments

x

an object of class summary.JointAI or JointAI

digits

the minimum number of significant digits to be printed in values.

scientific

A penalty to be applied when deciding to print numeric values in fixed or exponential notation, by default the value obtained from getOption("scipen")

...

currently not used

object

object inheriting from class 'JointAI'

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

quantiles

posterior quantiles

subset

subset of parameters/variables/nodes (columns in the MCMC sample). Follows the same principle as the argument monitor_params in *_imp.

exclude_chains

optional vector of the index numbers of chains that should be excluded

outcome

optional; vector identifying for which outcomes the summary should be given, either by specifying their indices, or their names (LHS of the respective model formulas as character string).

missinfo

logical; should information on the number and proportion of missing values be included in the summary?

warn

logical; should warnings be given? Default is TRUE.

mess

logical; should messages be given? Default is TRUE.

parm

same as subset (for consistency with confint method for other types of objects)

level

confidence level (default is 0.95)

Value

summary() returns an object of class summary.JointAI, a list with elements call, start, end and thin (the iterations used), nchain (the number of chains used), res (a list with the posterior summaries per sub-model), outcome, missinfo (the result of get_missinfo(), if missinfo = TRUE), analysis_type and size (the number of observations per level).

coef() returns a list with one named vector of posterior means per sub-model, confint() a list with one matrix of posterior quantiles per sub-model. The print() methods are called for their side effect and return x invisibly (print.Dmat: NULL).

See Also

The model fitting functions lm_imp, glm_imp, clm_imp, lme_imp, glme_imp, survreg_imp and coxph_imp, and the vignette Parameter Selection for examples how to specify the parameter subset.

Examples


## Not run: 
mod1 <- lm_imp(y ~ C1 + C2 + M2, data = wideDF, n.iter = 100)

summary(mod1, missinfo = TRUE)
coef(mod1)
confint(mod1)

## End(Not run)


Description

In cumulative logit models, the effects of the variables given in nonprop differ between the categories of the outcome.

Usage

print_nonprop_predvars(info)

Arguments

info

the model information of the sub-model (an element of info_list); the variables are in the attribute nonprop of info$lp.

Value

NULL, invisibly; called for the printed output.


Description

Print the coefficients of non-proportional effects (used in list_models())

Usage

print_nonprop_regcoef(info, data_list, priors)

Arguments

info

the model information of the sub-model (an element of info_list); the coefficients are in the attribute nonprop of the elements of info$parelmts, with one element per category of the outcome (except the first).

data_list

the data list passed to JAGS (for the hyper-parameters of the prior).

priors

logical; should the prior be printed?

Value

NULL, invisibly; called for the printed output.


Description

For each grouping level with random effects: the random effects with their variables, and their covariance matrix with its prior, as in the JAGS model (ranef_priors()): a Gamma prior for the precision of a single random effect, Gamma priors for the diagonal precision matrix with rd_vcov = "indep", and otherwise a Wishart prior for the precision matrix, with Gamma priors for the diagonal of its scale matrix. With rd_vcov = "full", the random effects of several sub-models have one covariance matrix; the sub-models that share it are named.

Usage

print_ranefs(info, data_list, priors)

Arguments

info

the model information of the sub-model (an element of info_list).

data_list

the data list passed to JAGS (for the hyper-parameters of the priors).

priors

logical; should the priors be printed?

Value

NULL, invisibly; called for the printed output.


Description

Multinomial models have a set of coefficients per category (except the reference category); they are listed per category, also when they are in several design matrices (mixed models).

Usage

print_regcoef(info, data_list, priors)

Arguments

info

the model information of the sub-model (an element of info_list).

data_list

the data list passed to JAGS (for the hyper-parameters of the prior).

priors

logical; should the prior be printed?

Value

NULL, invisibly; called for the printed output.


Description

Print the truncation of a sub-model (used in list_models())

Usage

print_trunc(trunc)

Arguments

trunc

numeric vector of length two with the lower and upper limit of the truncation (NA if there is no limit), as in the element trunc of the model information.

Value

NULL, invisibly; called for the printed output.


Part of the shift of the random effects that depends on covariates

Description

The shift of the random effects of group g is ⁠delta_g = mu(x_g) - A mu_s(x_g)⁠, with x_g the covariates in the means of the random effects of that group. It is affine in x_g: ⁠delta_g = delta + sum_w slope_w * x_gw⁠, with delta from ranef_shift(). Usually, slope_w is zero for each covariate (the covariates drop out, because the fixed effects are transformed back consistently), so that the data are not needed. It is not zero, e.g., in y ~ C1 * time + (time | id) + (C1 | center): the part of C1:time that the back-transformation moves into the coefficient of C1 belongs to the center-level random slope of C1, not to the id-level random intercept.

Usage

ranef_covariate_shift(part, A_part, MCMC, rescaled, coefs, scale_pars,
  data_list)

Arguments

part

one outcome of a block of random effects: element of the parts of a block (get_ranef_blocks()), with info, lvl_info and cols.

A_part

transformation matrix of the random effects of this outcome (ranef_transformation()).

MCMC

MCMC sample (matrix) on the scale used in JAGS.

rescaled

MCMC sample (matrix) in which the coefficients are already transformed back (rescale_coefs()).

coefs

data.frame with one row per regression coefficient (do.call(rbind, get_coef_names(info_list))); used to find the coefficients in the means of the random effects.

scale_pars

data.frame of scaling parameters (columns center and scale, one row per design-matrix column, named by the column), with centre 0 and scale 1 for columns that are not scaled.

data_list

data list passed to JAGS (for the names of design-matrix columns).

Value

List with one element per covariate for which slope_w is not zero: w (column name), matrix and col (data matrix and column number), and slope (matrix with one row per iteration and one column per random effect of this outcome).


Fixed-effects terms in the means of the random effects

Description

With hierarchical centring, the mean of a random effect contains fixed effects: the intercept and covariates of the level (random intercept), the coefficient of the random-slope variable and its cross-level interactions (random slopes).

Usage

ranef_mean_terms(lvl_info, data_list)

Arguments

lvl_info

hierarchical-centring information of one grouping level (element of hc_list$hcvars of a sub-model).

data_list

data list passed to JAGS (for the names of design-matrix columns).

Value

data.frame with one row per term: rd_effect (the random effect whose mean contains the term), coef_term (column name of the term, to find its coefficient), w (column name of the covariate the coefficient is multiplied with; NA for a constant, i.e. the intercept or the coefficient of the random-slope variable itself), and w_matrix and w_col (data matrix and column number of w; NA for a constant).


Shift delta of the random effects of one outcome and level

Description

⁠b = A b_s + delta⁠ with ⁠delta = mu(0) - A mu_s(0)⁠: the difference between the means of the random effects on the original and the scaled scale, evaluated at covariate values 0 (the covariates drop out when the fixed effects are transformed consistently, so any value would do). On the original scale, only the constant terms remain; on the scaled scale, a covariate w at 0 has the value -c_w / s_w.

Usage

ranef_shift(part, A_part, MCMC, rescaled, coefs, scale_pars, data_list)

Arguments

part

one outcome of a block of random effects: element of the parts of a block (get_ranef_blocks()), with info, lvl_info and cols.

A_part

transformation matrix of the random effects of this outcome (ranef_transformation()).

MCMC

MCMC sample (matrix) on the scale used in JAGS.

rescaled

MCMC sample (matrix) in which the coefficients are already transformed back (rescale_coefs()).

coefs

data.frame with one row per regression coefficient (do.call(rbind, get_coef_names(info_list))); used to find the coefficients in the means of the random effects.

scale_pars

data.frame of scaling parameters (columns center and scale, one row per design-matrix column, named by the column), with centre 0 and scale 1 for columns that are not scaled.

data_list

data list passed to JAGS (for the names of design-matrix columns).

Value

Matrix with one row per iteration and one column per random effect.


Transformation matrix A for the random effects of one outcome and level

Description

The random-slope variables enter JAGS as (z_j - c_j) / s_j, so ⁠sum_j b_s,j * (z_j - c_j) / s_j = sum_j (A b_s)_j * z_j⁠ with A[j, j] = 1 / s_j and, in the row of the random intercept, A[1, j] = -c_j / s_j: the centring is the same for all observations of a group and moves to the random intercept.

Usage

ranef_transformation(lvl_info, scale_pars)

Arguments

lvl_info

hierarchical-centring information of one grouping level (element of hc_list$hcvars of a sub-model).

scale_pars

data.frame of scaling parameters (columns center and scale, one row per design-matrix column, named by the column), with centre 0 and scale 1 for columns that are not scaled.

Details

Without random intercept, the random-slope variables are not centred (get_uncentred_columns()), so that only the scaling is undone here.

Value

Square matrix, one row and column per random effect.


Extract terms by grouping variables from a formula

Description

This function takes a formula as input, extracts terms that are associated with grouping variables, and organizes them by grouping variable.

Usage

rd_terms_by_grouping(formula)

Arguments

formula

a formula object

Value

a named list of one-sided formulas, where each name corresponds to a grouping variable and the formula contains all terms associated with that grouping variable.


Extract the random effects variance covariance matrix

Description

Returns the posterior mean of the variance-covariance matrix/matrices of the random effects in a fitted JointAI object.

Usage

rd_vcov(object, outcome = NULL, start = NULL, end = NULL, thin = NULL,
  exclude_chains = NULL, mess = TRUE, warn = TRUE)

Arguments

object

object inheriting from class 'JointAI'

outcome

optional; vector of integers giving the indices of the outcomes for which the random effects variance-covariance matrix/matrices should be returned.

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

exclude_chains

optional vector of the index numbers of chains that should be excluded

mess

logical; should messages be given? Default is TRUE.

warn

logical; should warnings be given? Default is TRUE.

Value

A list with one element per selected outcome (sub-model), each a list with one matrix per grouping level: the posterior mean of the variance-covariance matrix of the random effects, with rows and columns named by the random effects. When only one outcome is selected, the list for this outcome is returned directly.

Examples


mod <- lme_imp(y ~ C1 + time + (time | id), data = longDF, n.iter = 100,
               mess = FALSE)

rd_vcov(mod)



Set all elements of a difftime object to the same, largest meaningful unit

Description

Set all elements of a difftime object to the same, largest meaningful unit

Usage

reformat_difftime(dt)

Arguments

dt

a difftime object (potentially a vector of difftimes)


Scale columns without centring them

Description

Sets the centre of the given columns to 0 and their scale to the root mean square (as scale(x, center = FALSE)), calculated, like the other scaling parameters, from one value per group of the level of the data matrix (the data matrices in Mlist have one row per group). Columns that are not scaled at all are not changed.

Usage

remove_centring(scale_pars, columns, Mlist)

Arguments

scale_pars

list of data.frames of scaling parameters, one per data matrix (Mlist$scale_pars).

columns

character vector of column names (get_uncentred_columns()).

Mlist

list of data matrices and related information (divide_matrices()).

Value

scale_pars with the changed rows.


Remove grouping part from (random effects) formula

Description

Removes the part after (and including) the pipe symbol (|) in a formula.

Usage

remove_formula_grouping(formula)

Arguments

formula

A formula object (NOT a list of formulas)

Value

A list of one-sided formula objects without the grouping part, split by grouping variable

See Also

remove_grouping()


Remove grouping part from (random effects) formulas

Description

Applies remove_formula_grouping() to a list of formulas.

Usage

remove_grouping(formulas)

Arguments

formulas

A list of formula objects (or NULL)

Value

A list of formula objects without the grouping part

See Also

remove_formula_grouping()


Remove the labelled class from a vector

Description

Remove the labelled class from a vector

Usage

remove_labelled_class(x)

Arguments

x

a vector of class "labelled" or "haven_labelled"

Value

x without the labelled classes (and without classes that only describe the base type), so that e.g. a numeric vector is plain numeric again; other attributes are kept


Remove the left hand side of a (list of) formula(s)

Description

Internal function; used in divide_matrices, get_models and help functions (2022-02-05)

Usage

remove_lhs(formula)

Arguments

formula

a formula object or a list of formula objects

Value

A formula object or a list of formula objects.


Replace NaN values with NA

Description

Replace NaN values with NA

Usage

replace_nan_with_na(x)

Arguments

x

a vector (also works for matrices and scalars)

Value

the vector (or object like the input) with NaN values replaced by NA


Transform the MCMC sample back to the scale of the original data

Description

Continuous covariates are centred and scaled before they are passed to JAGS (see get_scale_pars()). After sampling, all parameters that depend on this scaling are transformed back, so that they refer to the original variables: the regression coefficients, thresholds of ordinal models and coefficients of the baseline hazard (rescale_coefs()), and the random effects and their variance-covariance matrices (rescale_ranefs()).

Usage

rescale(MCMC, coefs, scale_pars, info_list, data_list, groups)

Arguments

MCMC

MCMC sample of one chain (mcmc object or matrix), on the scale used in JAGS.

coefs

data.frame with one row per regression coefficient (do.call(rbind, get_coef_names(info_list))).

scale_pars

data.frame of scaling parameters (columns center and scale, one row per design-matrix column, named by the column; do.call(rbind, unname(Mlist$scale_pars))). NA means not scaled.

info_list

list with the model info of each sub-model.

data_list

data list passed to JAGS (for the names of design-matrix columns).

groups

list of grouping information (Mlist$groups; for the number of groups per level).

Details

Used by model_imp() and add_samples(), and by the package remiod (frozen: the arguments and the returned object must not change).

Value

Matrix with the same columns as MCMC, on the original scale.


Transform regression coefficients back to the original scale

Description

In JAGS, a covariate x enters a linear predictor as (x - center) / scale, with coefficient beta_s. On the original scale:

Usage

rescale_coefs(MCMC, coefs, scale_pars, info_list, data_list)

Arguments

MCMC

MCMC sample of one chain (mcmc object or matrix), on the scale used in JAGS.

coefs

data.frame with one row per regression coefficient (do.call(rbind, get_coef_names(info_list))).

scale_pars

data.frame of scaling parameters (columns center and scale, one row per design-matrix column, named by the column), as in rescale(), but without missing values (centre 0 and scale 1 for columns that are not scaled).

info_list

list with the model info of each sub-model.

data_list

data list passed to JAGS (for the names of design-matrix columns).

Details

Models without intercept have other parameters that take the role of the intercept and are shifted in the same way: the thresholds of ordinal models (⁠gamma_<y>[k]⁠; with the non-proportional effects of category k) and the coefficients of the baseline hazard of proportional hazards and joint models (⁠beta_Bh0_<y>⁠; all by the same amount, because the rows of the B-spline basis sum to 1).

Cross-level interactions in the mean of a random slope (hierarchical centring; e.g. C1:time with (time | id)) enter JAGS as the product of the separately scaled variables w (higher level) and z (random-slope variable): (w - c_w) / s_w * (z - c_z) / s_z. The coefficient is divided by s_w * s_z, the coefficients of w and z change by -beta_s * c_z / (s_w * s_z) and -beta_s * c_w / (s_w * s_z), and the intercept by +beta_s * c_w * c_z / (s_w * s_z).

A linear predictor is identified by the outcome and, for models with category-specific coefficients (e.g. multinomial models), the category (coefs$outcat; NA otherwise). All matching is done by name: parameters by their name in MCMC (coefs$coef), scaling parameters by the exact name of the design-matrix column (coefs$varname; scale_pars_rows()).

Value

Matrix with the same columns as MCMC; the regression coefficients, thresholds and coefficients of the baseline hazard are transformed back, all other parameters are unchanged.


Transform random effects and their covariance matrices back

Description

In JAGS, the random effects b of a grouping level enter the linear predictor as ⁠sum_j b_j * (z_j - c_j) / s_j⁠, with z_1 = 1 (random intercept) and the random-slope variables z_j, each centred and scaled separately. Written as a function of the original z, this gives the random effects on the original scale:

Usage

rescale_ranefs(rescaled, MCMC, coefs, scale_pars, info_list, data_list, groups)

Arguments

rescaled

MCMC sample (matrix) in which the coefficients are already transformed back (rescale_coefs()).

MCMC

MCMC sample of one chain on the scale used in JAGS (mcmc object or matrix).

coefs

data.frame with one row per regression coefficient (do.call(rbind, get_coef_names(info_list))); used to find the coefficients in the means of the random effects.

scale_pars

data.frame of scaling parameters (columns center and scale, one row per design-matrix column, named by the column), with centre 0 and scale 1 for columns that are not scaled.

info_list

list with the model information of each sub-model (get_model_info()).

data_list

data list passed to JAGS (for the names of design-matrix columns).

groups

list of grouping information (Mlist$groups; for the number of groups per level, and to find the rows of covariates per group).

Details

b = A b_s + delta,     D = A D_s A'

A does not need the data, so the random effects are transformed back also when a random-slope variable has missing values. delta usually does not need the data either. If it depends on covariates (see ranef_covariate_shift()), the values of each group are used: observed or, if missing, imputed values (if they were monitored). Without them, the random effects of that group are set to NA, with a warning.

The random effects are transformed per "block": the random effects that share one covariance matrix (get_ranef_blocks()). Usually, a block holds the random effects of one outcome at one grouping level; with rd_vcov = "full", it holds those of several outcomes, and A then has one submatrix on the diagonal per outcome (zero elsewhere).

Value

rescaled, with the random effects and their covariance matrices transformed back.


Transform the covariance matrix of random effects back: D = A D_s A'

Description

Transform the covariance matrix of random effects back: D = A D_s A'

Usage

rescale_vcov(MCMC, D_name, A)

Arguments

MCMC

MCMC sample (matrix); the elements of the covariance matrix are the columns ⁠<D_name>[i,j]⁠ with i <= j (as monitored in JAGS).

D_name

name of the covariance matrix, e.g. "D_y_id".

A

transformation matrix (ranef_transformation()).

Value

MCMC with the covariance matrix transformed back, in each iteration; unchanged if the matrix is not (completely) in the sample.


Extract residuals from an object of class JointAI

Description

Extract residuals from an object of class JointAI

Usage

## S3 method for class 'JointAI'
residuals(object, type = c("working", "pearson",
  "response"), warn = TRUE, ...)

Arguments

object

object inheriting from class 'JointAI'

type

type of residuals: "working" (default), "pearson" or "response". In models with more than one model formula, one value applies to all outcomes, and a named vector sets the type per outcome (outcomes that are not named get "working").

warn

logical; should warnings be given? Default is TRUE.

...

currently not used

Value

A numeric vector of residuals, or, for models with more than one model formula, a list with one such vector per outcome.

Note

Examples

mod <- glm_imp(B1 ~ C1 + C2 + O1, data = wideDF, n.iter = 100,
               family = binomial(), mess = FALSE)
summary(residuals(mod, type = 'response'))
summary(residuals(mod, type = 'working'))



Resolve family object

Description

Converts a family specification (character string, function, or family object) to a family object.

Usage

resolve_family_obj(family)

Arguments

family

Family object, character string, or function.

Value

A family object or NULL.

Note

Helper function used in prep_arglist().


Restore variable labels

Description

Restore variable labels

Usage

restore_var_labels(data, var_labels)

Arguments

data

a data.frame

var_labels

a named list of variable labels (the "label" attributes of the variables in the original data, NULL if there was none)

Value

data, where variables that lost their "label" attribute have it again


Scaling parameters of design-matrix columns

Description

Finds the rows by the exact column name. (Indexing the rows of a data.frame with names, scale_pars[columns, ], also accepts a partial match: "age" would find the row "age_sq" if there is no row "age".)

Usage

scale_pars_rows(scale_pars, columns)

Arguments

scale_pars

data.frame of scaling parameters (columns center and scale, one row per design-matrix column, named by the column).

columns

character vector of column names.

Value

data.frame with one row per element of columns, in that order; the values are NA for a name that has no row in scale_pars.


Keep the requested elements of nodes that were monitored as a whole

Description

The samples of a node that was monitored as a whole instead of some of its elements (see get_monitor_nodes()) are reduced to the requested elements, in the requested order, at the position of the node. All other columns stay as they are. The result is the same as if the elements had been monitored.

Usage

select_monitored_columns(mcmc, var_names, monitor_nodes)

Arguments

mcmc

an mcmc.list with the samples (one column per element)

var_names

a character vector with the requested names of nodes and elements (as given to get_monitor_nodes())

monitor_nodes

a character vector with the names that were given to JAGS, as obtained from get_monitor_nodes()

Value

an mcmc.list


Specify reference categories for all categorical covariates in the model

Description

The function is a helper function that asks questions and, depending on the answers given by the user, returns the input for the argument refcats in the main analysis functions *_imp.

Usage

set_refcat(data, formula, covars, auxvars = NULL)

Arguments

data

a data.frame

formula

optional; model formula or a list of formulas (used to select subset of relevant columns of data)

covars

optional; vector containing the names of relevant columns of data

auxvars

optional; formula containing the names of relevant columns of data that should be considered additionally to the columns occurring in the formula

Details

The arguments formula, covars and auxvars can be used to specify a subset of the data to be considered. If non of these arguments is specified, all variables in data will be considered.

Value

Invisibly, the value to be passed to the argument refcats: either one of "first", "last" or "largest", or a named numeric vector with the index of the reference category of each categorical variable.

Examples

## Not run: 
# Example 1: set reference categories for the whole dataset and choose
# answer option 3:
set_refcat(data = NHANES)
3

# insert the returned string as argument refcats
mod1 <- lm_imp(SBP ~ age + race + creat + educ, data = NHANES,
               refcats = 'largest')

# Example 2:
# specify a model formula
fmla <- SBP ~ age + gender + race + bili + smoke + alc

# write the output of set_refcat to an object
ref_mod2 <- set_refcat(data = NHANES, formula = fmla)
4
2
5
1
1

# enter the output in the model specification
mod2 <- lm_imp(formula = fmla, data = NHANES, refcats = ref_mod2,
               n.adapt = 0)

## End(Not run)


Simulated Longitudinal Data in Long and Wide Format

Description

This data was simulated to mimic data from a longitudinal cohort study following mothers and their child from birth until approximately 4 years of age. It contains 2400 observations of 200 mother-child pairs. Children's BMI and head circumference was measured repeatedly and their age in months was recorded at each measurement. Furthermore, the data contain several baseline variables with information on the mothers' demographics and socio-economic status.

Usage

simLong

simWide

Format

simLong: A data frame in long format with 2400 rows and 16 variables

simWide: A data frame in wide format with 200 rows and 81 variables

An object of class data.frame with 2400 rows and 16 columns.

An object of class data.frame with 200 rows and 81 columns.

Baseline covariates

(in simLong and simWide)

GESTBIR

gestational age at birth (in weeks)

ETHN

ethnicity (binary: European vs. other)

AGE_M

age of the mother at intake

HEIGHT_M

height of the mother (in cm)

PARITY

number of times the mother has given birth (binary: 0 vs. >=1)

SMOKE

smoking status of the mother during pregnancy (3 ordered categories: never smoked during pregnancy, smoked until pregnancy was known, continued smoking in pregnancy)

EDUC

educational level of the mother (3 ordered categories: low, mid, high)

MARITAL

marital status (3 categories)

ID

subject identifier

Long-format variables

(only in simLong)

time

measurement occasion/visit (by design, children should be measured at/around 1, 2, 3, 4, 7, 11, 15, 20, 26, 32, 40 and 50 months of age)

age

child age at measurement time in months

bmi

child BMI

hc

child head circumference in cm

hgt

child height in cm

wgt

child weight in gram

sleep

sleeping behaviour of the child (3 ordered categories)

Wide-format variables

(only in simWide)

age1, age2, age3, age4, age7, age11, age15, age20, age26, age32, age40, age50

child age at the repeated measurements in months

bmi1, bmi2, bmi3, bmi4, bmi7, bmi11, bmi15, bmi20, bmi26, bmi32, bmi40, bmi50

repeated measurements of child BMI

hc1, hc2, hc3, hc4, hc7, hc11, hc15, hc20, hc26, hc32, hc40, hc50

repeated measurements of child head circumference in cm

hgt1, hgt2, hgt3, hgt4, hgt7, hgt11, hgt15, hgt20, hgt26, hgt32, hgt40, hgt50

repeated measurements of child height in cm

wgt1, wgt2, wgt3, wgt4, wgt7, wgt11, wgt15, wgt20, wgt26, wgt32, wgt40, wgt50

repeated measurements of child weight in gram

sleep1, sleep2, sleep3, sleep4, sleep7, sleep11, sleep15, sleep20, sleep26, sleep32, sleep40, sleep50

repeated measurements of child sleep behaviour (3 ordered categories)

Examples

 summary(simLong)
 summary(simWide)


Split a list of formulas into fixed and random effects parts

Description

Calls extract_fixef_formula() and extract_ranef_formula() on each formula in a list to create one list of the fixed effects formulas and one list containing the random effects formulas.

Usage

split_formula_list(formula)

Arguments

formula

a formula or a list of formula objects

Details

Internal function, used in *_imp() (2022-02-06)

Value

A list with two elements, fixed and random, each of which is a named list of formula objects (or NULL)


Calculate the sum of the computational duration of a JointAI object

Description

Calculate the sum of the computational duration of a JointAI object

Usage

sum_duration(object, by = c("all", "phase", "run", "chain", "phase and run",
  "run and phase"))

Arguments

object

object of class JointAI

by

grouping; one of "all" (default) to calculate the sum over all chains and runs and both the adaptive and sampling phase, "phase" to get the sum over all chains and runs per phase, "run" to get the duration per run (over both phases), "chain" to get the sum per chain over both phases and all runs, "phase and run" (or "run and phase") to get the sum over all chains, separately per phase and run. NULL (the default in earlier versions) is the same as "all".

Value

The duration(s), as difftime: for by = "all" a single value; for "phase" a list with elements adapt and sample; for "run" a named vector with one value per run; for "chain" a named vector with one value per chain (a single value total when the chains were not run in parallel); for "phase and run" a list with elements adapt and sample, each a named vector with one value per run.

Examples


mod <- lm_imp(y ~ C1 + C2, data = wideDF, n.iter = 100, mess = FALSE)

sum_duration(mod)
sum_duration(mod, by = "phase")



Create traceplots for a MCMC sample

Description

Creates a set of traceplots from the MCMC sample of an object of class 'JointAI'.

Usage

traceplot(object, ...)

## S3 method for class 'JointAI'
traceplot(object, start = NULL, end = NULL,
  thin = NULL, subset = c(analysis_main = TRUE), outcome = NULL,
  exclude_chains = NULL, nrow = NULL, ncol = NULL, use_ggplot = FALSE,
  warn = TRUE, mess = TRUE, ...)

Arguments

object

object inheriting from class 'JointAI'

...

Arguments passed on to graphics::matplot

lty,lwd,lend

vector of line types, widths, and end styles. The first element is for the first column, the second element for the second column, etc., even if lines are not plotted for all columns. Line types will be used cyclically until all plots are drawn.

col

vector of colors. Colors are used cyclically.

cex

vector of character expansion sizes, used cyclically. This works as a multiple of par("cex"). NULL is equivalent to 1.0.

bg

vector of background (fill) colors for the open plot symbols given by pch = 21:25 as in points. The default NA corresponds to the one of the underlying function plot.xy.

add

logical. If TRUE, plots are added to current one, using points and lines.

verbose

logical. If TRUE, write one line of what is done.

start

the first iteration of interest (see window.mcmc)

end

the last iteration of interest (see window.mcmc)

thin

thinning interval (integer; see window.mcmc). For example, thin = 1 (default) will keep the MCMC samples from all iterations; thin = 5 would only keep every 5th iteration.

subset

subset of parameters/variables/nodes (columns in the MCMC sample). Follows the same principle as the argument monitor_params in *_imp.

outcome

optional; vector identifying a subset of sub-models included in the output, either by specifying their indices (using the order used in the list of model formulas), or their names (LHS of the respective model formula as character string)

exclude_chains

optional vector of the index numbers of chains that should be excluded

nrow

optional; number of rows in the plot layout; automatically chosen if unspecified

ncol

optional; number of columns in the plot layout; automatically chosen if unspecified

use_ggplot

logical; Should ggplot be used instead of the base graphics?

warn

logical; should warnings be given? Default is TRUE.

mess

logical; should messages be given? Default is TRUE.

Value

With use_ggplot = TRUE (only for objects of class 'JointAI') a ggplot object. Otherwise, the plots are drawn with base graphics and NULL is returned invisibly.

See Also

summary.JointAI, *_imp, densplot
The vignette Parameter Selection contains some examples how to specify the parameter subset.

Examples

# fit a JointAI model
mod <- lm_imp(y ~ C1 + C2 + M1, data = wideDF, n.iter = 100)


# Example 1: simple traceplot
traceplot(mod)


# Example 2: ggplot version of traceplot
traceplot(mod, use_ggplot = TRUE)


# Example 5: changing how the ggplot version looks (using ggplot syntax)
library(ggplot2)

traceplot(mod, use_ggplot = TRUE) +
  theme(legend.position = 'bottom') +
  xlab('iteration') +
  ylab('value') +
  scale_color_discrete(name = 'chain')



Convert two-value vectors to factors

Description

Convert two-value vectors to factors

Usage

two_value_to_factor(x)

Arguments

x

a vector

Value

the vector converted to a factor if it has exactly two unique (non-missing) values and is not already a factor; otherwise the input


Write the arguments of Surv() on the left-hand side without names

Description

The names of the survival time and event variables are taken from the position of the arguments of Surv() (idSurv()), and the name of the outcome from the text of the left-hand side. Named arguments, e.g. Surv(time = futime, event = status) or Surv(futime, time2 = status), are therefore rewritten to Surv(futime, status). This is only done for right-censored data, i.e., the arguments time and, optionally, time2 or event; other combinations are left unchanged (and give an error later on).

Usage

unname_surv_args(fixed)

Arguments

fixed

a formula or a list of formulas (other elements, e.g. NULL, are returned unchanged)

Value

fixed, with the left-hand side Surv() written with unnamed arguments where it had named arguments


Set the fitted values and residuals of a JointAI object

Description

Calculates the fitted values and (working) residuals from the current MCMC sample of the object. If they cannot be calculated (e.g., because there is no sample or the regression coefficients are not monitored), they are removed from the object, so that no values from an earlier sample remain.

Usage

update_fitted_residuals(object)

Arguments

object

object of class JointAI (or the object that is being created in model_imp() and add_samples()).

Value

object with the updated elements fitted.values and residuals.


Create data.frame from variable term and data

Description

Create data.frame from variable term and data

Usage

varname_to_modelframe(varname, data)

Arguments

varname

character string giving the variable name or model term

data

a data.frame containing the variables mentioned in varname

Value

a data.frame


Write exp() so that JAGS accepts a vector as its argument

Description

In the quadrature part of a joint model, the underlying value of a time-varying covariate is a vector (e.g., mugk_x[ii, 1:15]), but JAGS does not accept a vector as argument of exp(). Each exp(a) is replaced by (exp(1)^(a)), in which the outer parentheses keep the precedence of the original function call. Used in paste_linpred_jm() and paste_jm_column().

Usage

vectorize_exp(x)

Arguments

x

character string with (part of) a JAGS expression

Value

The character string with all calls to exp() replaced.


Warn about unknown arguments of the ⁠*_imp()⁠ functions

Description

Arguments of the ⁠*_imp()⁠ functions that are not arguments of model_imp() end up in the ... of model_imp(), where they are not used. A misspelled argument (e.g., n.itre instead of n.iter) would otherwise be ignored silently (#114). A warning rather than an error, so that existing code keeps running.

Usage

warn_unknown_args(arg_names, known, warn = TRUE)

Arguments

arg_names

character vector; the names of the arguments that model_imp() was called with

known

character vector; the names of the arguments that are used: the formal arguments of model_imp() and the elements that prep_arglist() adds (thecall)

warn

logical; if FALSE, no warning is given

Details

used in model_imp() (2026-11-06)

Value

NULL (invisibly); called for its warning


Cross-sectional example dataset

Description

A simulated cross-sectional dataset.

Usage

data(wideDF)

Format

A simulated data frame with 100 rows and 13 variables:

C1

continuous, complete variable

C2

continuous, incomplete variable

B1

binary, complete variable

B2

binary, incomplete variable

M1

unordered factor; complete variable

M2

unordered factor; incomplete variable

O1

ordered factor; complete variable

O2

ordered factor; incomplete variable

L1

continuous, complete variable

L2

continuous incomplete variable

id

id (grouping) variable

time

continuous complete variable

y

continuous, complete variable