Type: Package
Title: Mixed Models for Repeated Measures
Version: 0.3.15
Description: Mixed models for repeated measures (MMRM) are a popular choice for analyzing longitudinal continuous outcomes in randomized clinical trials and beyond; see Cnaan, Laird and Slasor (1997) <doi:10.1002/(SICI)1097-0258(19971030)16:20%3C2349::AID-SIM667%3E3.0.CO;2-E> for a tutorial and Mallinckrodt, Lane, Schnell, Peng and Mancuso (2008) <doi:10.1177/009286150804200402> for a review. This package implements MMRM based on the marginal linear model without random effects using Template Model Builder ('TMB') which enables fast and robust model fitting. Users can specify a variety of covariance matrices, weight observations, fit models with restricted or standard maximum likelihood inference, perform hypothesis testing with Satterthwaite or Kenward-Roger adjustment, and extract least square means estimates by using 'emmeans'.
License: Apache License 2.0
URL: https://openpharma.github.io/mmrm/
BugReports: https://github.com/openpharma/mmrm/issues
Depends: R (≥ 4.1)
Imports: checkmate (≥ 2.0), generics, lifecycle, Matrix, methods, nlme, parallel, Rcpp, Rdpack, stats, stringr, tibble, TMB (≥ 1.9.1), utils
Suggests: broom.helpers, car (≥ 3.1.2), cli, clubSandwich, clusterGeneration, dplyr, emmeans (≥ 1.6), estimability, ggplot2, glmmTMB, hardhat, knitr, lme4, MASS, microbenchmark, mockery, parallelly (≥ 1.32.0), parsnip (≥ 1.1.0), purrr, rmarkdown, sasr, scales, testthat (≥ 3.0.0), tidymodels, withr, xml2
LinkingTo: Rcpp, RcppEigen, testthat, TMB (≥ 1.9.1)
VignetteBuilder: knitr
RdMacros: Rdpack
Config/testthat/edition: 3
Encoding: UTF-8
Language: en-US
LazyData: true
NeedsCompilation: yes
RoxygenNote: 7.3.2
Collate: 'between-within.R' 'catch-routine-registration.R' 'component.R' 'cov_struct.R' 'data.R' 'empirical.R' 'fit.R' 'kenwardroger.R' 'mmrm-methods.R' 'mmrm-package.R' 'utils.R' 'residual.R' 'utils-nse.R' 'utils-formula.R' 'satterthwaite.R' 'skipping.R' 'tidiers.R' 'testing.R' 'tmb-methods.R' 'tmb.R' 'interop-emmeans.R' 'interop-parsnip.R' 'interop-car.R' 'zzz.R'
Packaged: 2025-06-10 09:46:41 UTC; Daniel
Author: Daniel Sabanes Bove ORCID iD [aut, cre], Liming Li ORCID iD [aut], Julia Dedic [aut], Doug Kelkhoff [aut], Kevin Kunzmann [aut], Brian Matthew Lang [aut], Christian Stock [aut], Ya Wang [aut], Craig Gower-Page [ctb], Dan James [aut], Jonathan Sidi [aut], Daniel Leibovitz [aut], Daniel D. Sjoberg ORCID iD [aut], Nikolas Ivan Krieger ORCID iD [aut], Lukas A. Widmer ORCID iD [ctb], Boehringer Ingelheim Ltd. [cph, fnd], Gilead Sciences, Inc. [cph, fnd], F. Hoffmann-La Roche AG [cph, fnd], Merck Sharp & Dohme, Inc. [cph, fnd], AstraZeneca plc [cph, fnd], inferential.biostatistics GmbH [cph, fnd]
Maintainer: Daniel Sabanes Bove <daniel.sabanes_bove@rconis.com>
Repository: CRAN
Date/Publication: 2025-06-10 10:50:02 UTC

mmrm Package

Description

mmrm implements mixed models with repeated measures (MMRM) in R.

Author(s)

Maintainer: Daniel Sabanes Bove daniel.sabanes_bove@rconis.com (ORCID)

Authors:

Other contributors:

See Also

Useful links:


Conduct type II/III hypothesis testing on the MMRM fit results.

Description

Conduct type II/III hypothesis testing on the MMRM fit results.

Usage

Anova.mmrm(
  mod,
  type = c("II", "III", "2", "3"),
  tol = sqrt(.Machine$double.eps),
  ...
)

Arguments

mod

(mmrm)
the fitted MMRM.

type

(string) type of test, "II", "III", '2', or '3'.

tol

(numeric) threshold blow which values are treated as 0.

...

not used.

Details

Anova will return anova object with one row per variable and columns ⁠Num Df⁠(numerator degrees of freedom), ⁠Denom Df⁠(denominator degrees of freedom), ⁠F Statistic⁠ and ⁠Pr(>=F)⁠.


Covariance Type Database

Description

An internal constant for covariance type information.

Usage

COV_TYPES

Format

A data frame with 5 variables and one record per covariance type:

name

The long-form name of the covariance structure type

abbr

The abbreviated name of the covariance structure type

habbr

The abbreviated name of the heterogeneous version of a covariance structure type (The abbreviated name (abbr) with a trailing "h" if the structure has a heterogeneous implementation or NA otherwise).

heterogeneous

A logical value indicating whether the covariance structure has a heterogeneous counterpart.

spatial

A logical value indicating whether the covariance structure is spatial.


Coerce into a Covariance Structure Definition

Description

[Stable]

Usage

as.cov_struct(x, ...)

## S3 method for class 'formula'
as.cov_struct(x, warn_partial = TRUE, ...)

Arguments

x

an object from which to derive a covariance structure. See object specific sections for details.

...

additional arguments unused.

warn_partial

(flag)
whether to emit a warning when parts of the formula are disregarded.

Details

A covariance structure can be parsed from a model definition formula or call. Generally, covariance structures defined using non-standard evaluation take the following form:

type( (visit, )* visit | (group /)? subject )

For example, formulas may include terms such as

us(time | subject)
cp(time | group / subject)
sp_exp(coord1, coord2 | group / subject)

Note that only sp_exp (spatial) covariance structures may provide multiple coordinates, which identify the Euclidean distance between the time points.

Value

A cov_struct() object.

Methods (by class)

See Also

Other covariance types: cov_struct(), covariance_types

Examples

# provide a covariance structure as a right-sided formula
as.cov_struct(~ csh(visit | group / subject))

# when part of a full formula, suppress warnings using `warn_partial = FALSE`
as.cov_struct(y ~ x + csh(visit | group / subject), warn_partial = FALSE)


Example Data on BCVA

Description

[Stable]

Usage

bcva_data

Format

A tibble with 10,000 rows and 7 variables:

Note

Measurements of BCVA (best corrected visual acuity) is a measure of how how many letters a person can read off of an eye chart using corrective lenses or contacts. This a common endpoint in ophthalmology trials.

Source

This is an artificial dataset.


Cache Data for mmrm Model Comparison

Description

[Stable]

Usage

cached_mmrm_results

Format

A list with following elements:

Note

The cached data for comparison is used for the vignettes generation. Please make sure that this data is refreshed before each package release by running the script data-raw/mmrm_review.R. Please make sure to install the mmrm package instead of using devtools::load_all() before running the script to achieve accurate timings.

Source

This is created based on simulations on FEV data and BCVA data.


Register mmrm For Use With car::Anova

Description

Register mmrm For Use With car::Anova

Usage

car_add_mmrm(quietly = FALSE)

Arguments

quietly

logical: should progress and error messages be suppressed?

Value

A logical value indicating whether registration was successful.


Check Suggested Dependency Against Version Requirements

Description

Check Suggested Dependency Against Version Requirements

Usage

check_package_version(pkg, ver = c(NA_character_, NA_character_))

Arguments

pkg

(string)
package name.

ver

(character)
of length 2 whose elements can be provided to numeric_version(), representing a minimum and maximum (inclusive) version requirement for interoperability. When NA, no version requirement is imposed. Defaults to no version requirement.

Value

A logical (invisibly) indicating whether the loaded package meets the version requirements. A warning is emitted otherwise.


Component Access for mmrm_tmb Objects

Description

[Stable]

Usage

component(
  object,
  name = c("cov_type", "subject_var", "n_theta", "n_subjects", "n_timepoints", "n_obs",
    "beta_vcov", "beta_vcov_complete", "varcor", "score_per_subject", "formula",
    "dataset", "n_groups", "reml", "convergence", "evaluations", "method", "optimizer",
    "conv_message", "call", "theta_est", "beta_est", "beta_est_complete", "beta_aliased",
    "x_matrix", "y_vector", "neg_log_lik", "jac_list", "theta_vcov", "full_frame",
    "xlev", "contrasts")
)

Arguments

object

(mmrm_tmb)
the fitted MMRM.

name

(character)
the component(s) to be retrieved.

Details

Available component() names are as follows:

Value

The corresponding component of the object, see details.

See Also

In the lme4 package there is a similar function getME().

Examples

fit <- mmrm(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data
)
# Get all available components.
component(fit)
# Get convergence code and message.
component(fit, c("convergence", "conv_message"))
# Get modeled formula as a string.
component(fit, c("formula"))


Define a Covariance Structure

Description

[Stable]

Usage

cov_struct(
  type = cov_types(),
  visits,
  subject,
  group = character(),
  heterogeneous = FALSE
)

Arguments

type

(string)
the name of the covariance structure type to use. For available options, see cov_types(). If a type abbreviation is used that implies heterogeneity (e.g. cph) and no value is provided to heterogeneous, then the heterogeneity is derived from the type name.

visits

(character)
a vector of variable names to use for the longitudinal terms of the covariance structure. Multiple terms are only permitted for the "spatial" covariance type.

subject

(string)
the name of the variable that encodes a subject identifier.

group

(string)
optionally, the name of the variable that encodes a grouping variable for subjects.

heterogeneous

(flag)

Value

A cov_struct object.

See Also

Other covariance types: as.cov_struct(), covariance_types

Examples

cov_struct("csh", "AVISITN", "USUBJID")
cov_struct("spatial", c("VISITA", "VISITB"), group = "GRP", subject = "SBJ")


Retrieve Associated Abbreviated Covariance Structure Type Name

Description

Retrieve Associated Abbreviated Covariance Structure Type Name

Usage

cov_type_abbr(type)

Arguments

type

(string)
either a full name or abbreviate covariance structure type name to collapse into an abbreviated type.

Value

The corresponding abbreviated covariance type name.


Retrieve Associated Full Covariance Structure Type Name

Description

Retrieve Associated Full Covariance Structure Type Name

Usage

cov_type_name(type)

Arguments

type

(string)
either a full name or abbreviate covariance structure type name to convert to a long-form type.

Value

The corresponding abbreviated covariance type name.


Covariance Types

Description

[Stable]

Usage

cov_types(
  form = c("name", "abbr", "habbr"),
  filter = c("heterogeneous", "spatial")
)

Arguments

form

(character)
covariance structure type name form. One or more of "name", "abbr" (abbreviation), or "habbr" (heterogeneous abbreviation).

filter

(character)
covariance structure type filter. One or more of "heterogeneous" or "spatial".

Value

A character vector of accepted covariance structure type names and abbreviations.

Abbreviations for Covariance Structures

Common Covariance Structures:

Structure Description Parameters (i, j) element
ad Ante-dependence m \sigma^{2}\prod_{k=i}^{j-1}\rho_{k}
adh Heterogeneous ante-dependence 2m-1 \sigma_{i}\sigma_{j}\prod_{k=i}^{j-1}\rho_{k}
ar1 First-order auto-regressive 2 \sigma^{2}\rho^{\left \vert {i-j} \right \vert}
ar1h Heterogeneous first-order auto-regressive m+1 \sigma_{i}\sigma_{j}\rho^{\left \vert {i-j} \right \vert}
cs Compound symmetry 2 \sigma^{2}\left[ \rho I(i \neq j)+I(i=j) \right]
csh Heterogeneous compound symmetry m+1 \sigma_{i}\sigma_{j}\left[ \rho I(i \neq j)+I(i=j) \right]
toep Toeplitz m \sigma_{\left \vert {i-j} \right \vert +1}
toeph Heterogeneous Toeplitz 2m-1 \sigma_{i}\sigma_{j}\rho_{\left \vert {i-j} \right \vert}
us Unstructured m(m+1)/2 \sigma_{ij}

where i and j denote i-th and j-th time points, respectively, out of total m time points, 1 \leq i, j \leq m.

Note

The ante-dependence covariance structure in this package refers to homogeneous ante-dependence, while the ante-dependence covariance structure from SAS ⁠PROC MIXED⁠ refers to heterogeneous ante-dependence and the homogeneous version is not available in SAS.

For all non-spatial covariance structures, the time variable must be coded as a factor.

Spatial Covariance structures:

Structure Description Parameters (i, j) element
sp_exp spatial exponential 2 \sigma^{2}\rho^{-d_{ij}}

where d_{ij} denotes the Euclidean distance between time points i and j.

See Also

Other covariance types: as.cov_struct(), cov_struct()


Calculation of Degrees of Freedom for One-Dimensional Contrast

Description

[Stable] Calculates the estimate, adjusted standard error, degrees of freedom, t statistic and p-value for one-dimensional contrast.

Usage

df_1d(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(numeric)
contrast vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with est, se, df, t_stat and p_val.

Examples

object <- mmrm(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data
)
contrast <- numeric(length(object$beta_est))
contrast[3] <- 1
df_1d(object, contrast)

Calculation of Degrees of Freedom for Multi-Dimensional Contrast

Description

[Stable] Calculates the estimate, standard error, degrees of freedom, t statistic and p-value for one-dimensional contrast, depending on the method used in mmrm().

Usage

df_md(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(matrix)
numeric contrast matrix, if given a numeric then this is coerced to a row vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with num_df, denom_df, f_stat and p_val (2-sided p-value).

Examples

object <- mmrm(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data
)
contrast <- matrix(data = 0, nrow = 2, ncol = length(object$beta_est))
contrast[1, 2] <- contrast[2, 3] <- 1
df_md(object, contrast)

Drop Items from an Indexible

Description

Drop elements from an indexible object (vector, list, etc.).

Usage

drop_elements(x, n)

Arguments

x

Any object that can be consumed by seq_along() and indexed by a logical vector of the same length.

n

(integer)
the number of terms to drop.

Value

A subset of x.


Format a Message to Emit When Tidymodels is Loaded

Description

Format a Message to Emit When Tidymodels is Loaded

Usage

emit_tidymodels_register_msg()

Value

A character message to emit. Either a ansi-formatted cli output if package 'cli' is available or a plain-text message otherwise.


Support for emmeans

Description

[Stable]

This package includes methods that allow mmrm objects to be used with the emmeans package. emmeans computes estimated marginal means (also called least-square means) for the coefficients of the MMRM. We can also e.g. obtain differences between groups by applying pairs() on the object returned by emmeans::emmeans().

Examples

fit <- mmrm(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data
)
if (require(emmeans)) {
  emmeans(fit, ~ ARMCD | AVISIT)
  pairs(emmeans(fit, ~ ARMCD | AVISIT), reverse = TRUE)
}

Empirical Starting Value

Description

Obtain empirical start value for unstructured covariance

Usage

emp_start(data, model_formula, visit_var, subject_var, subject_groups, ...)

Arguments

data

(data.frame)
data used for model fitting.

model_formula

(formula)
the formula in mmrm model without covariance structure part.

visit_var

(string)
visit variable.

subject_var

(string)
subject id variable.

subject_groups

(factor)
subject group assignment.

...

not used.

Details

This emp_start only works for unstructured covariance structure. It uses linear regression to first obtain the coefficients and use the residuals to obtain the empirical variance-covariance, and it is then used to obtain the starting values.

Value

A numeric vector of starting values.

Note

data is used instead of full_frame because full_frame is already transformed if model contains transformations, e.g. log(FEV1) ~ exp(FEV1_BL) will drop FEV1 and FEV1_BL but add log(FEV1) and exp(FEV1_BL) in full_frame.


Example Data on FEV1

Description

[Stable]

Usage

fev_data

Format

A tibble with 800 rows and 7 variables:

Note

Measurements of FEV1 (forced expired volume in one second) is a measure of how quickly the lungs can be emptied. Low levels of FEV1 may indicate chronic obstructive pulmonary disease (COPD).

Source

This is an artificial dataset.


Complete character Vector Names From Values

Description

Complete character Vector Names From Values

Usage

fill_names(x)

Arguments

x

(character or list)
value whose names should be completed from element values.

Value

A named vector or list.


Low-Level Fitting Function for MMRM

Description

[Stable]

This is the low-level function to fit an MMRM. Note that this does not try different optimizers or adds Jacobian information etc. in contrast to mmrm().

Usage

fit_mmrm(
  formula,
  data,
  weights,
  reml = TRUE,
  covariance = NULL,
  tmb_data,
  formula_parts,
  control = mmrm_control()
)

Arguments

formula

(formula)
model formula with exactly one special term specifying the visits within subjects, see details.

data

(data.frame)
input data containing the variables used in formula.

weights

(vector)
input vector containing the weights.

reml

(flag)
whether restricted maximum likelihood (REML) estimation is used, otherwise maximum likelihood (ML) is used.

covariance

(cov_struct)
A covariance structure type definition, or value that can be coerced to a covariance structure using as.cov_struct(). If no value is provided, a structure is derived from the provided formula.

tmb_data

(mmrm_tmb_data)
object.

formula_parts

(mmrm_tmb_formula_parts)
list with formula parts from h_mmrm_tmb_formula_parts().

control

(mmrm_control)
list of control options produced by mmrm_control().

Details

The formula typically looks like:

FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID)

which specifies response and covariates as usual, and exactly one special term defines which covariance structure is used and what are the visit and subject variables.

Always use only the first optimizer if multiple optimizers are provided.

Value

List of class mmrm_tmb, see h_mmrm_tmb_fit() for details. In addition, it contains elements call and optimizer.

Examples

formula <- FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID)
data <- fev_data
system.time(result <- fit_mmrm(formula, data, rep(1, nrow(fev_data))))

Fitting an MMRM with Single Optimizer

Description

[Stable]

This function helps to fit an MMRM using TMB with a single optimizer, while capturing messages and warnings.

Usage

fit_single_optimizer(
  formula,
  data,
  weights,
  reml = TRUE,
  covariance = NULL,
  tmb_data,
  formula_parts,
  ...,
  control = mmrm_control(...)
)

Arguments

formula

(formula)
the model formula, see details.

data

(data)
the data to be used for the model.

weights

(vector)
an optional vector of weights to be used in the fitting process. Should be NULL or a numeric vector.

reml

(flag)
whether restricted maximum likelihood (REML) estimation is used, otherwise maximum likelihood (ML) is used.

covariance

(cov_struct)
a covariance structure type definition as produced with cov_struct(), or value that can be coerced to a covariance structure using as.cov_struct(). If no value is provided, a structure is derived from the provided formula.

tmb_data

(mmrm_tmb_data)
object.

formula_parts

(mmrm_tmb_formula_parts)
object.

...

Additional arguments to pass to mmrm_control().

control

(mmrm_control)
object.

Details

fit_single_optimizer will fit the mmrm model using the control provided. If there are multiple optimizers provided in control, only the first optimizer will be used. If tmb_data and formula_parts are both provided, formula, data, weights, reml, and covariance are ignored.

Value

The mmrm_fit object, with additional attributes containing warnings, messages, optimizer used and convergence status in addition to the mmrm_tmb contents.

Examples

mod_fit <- fit_single_optimizer(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data,
  weights = rep(1, nrow(fev_data)),
  optimizer = "nlminb"
)
attr(mod_fit, "converged")

Flatten Expressions for Non-standard Evaluation

Description

Used primarily to support the parsing of covariance structure definitions from formulas, these functions flatten the syntax tree into a hierarchy-less grammar, allowing for parsing that doesn't abide by R's native operator precedence.

Usage

flatten_call(call)

flatten_expr(expr)

Arguments

call, expr

(language)
a language object to flatten.

Details

Where 1 + 2 | 3 in R's syntax tree is (|, (+, 1, 2), 3), flattening it into its visual order produces (1, +, 2, |, 3), which makes for more fluent interpretation of non-standard grammar rules used in formulas.

Value

A list of atomic values, symbols, infix operator names and subexpressions.

Functions


Format Covariance Structure Object

Description

Format Covariance Structure Object

Usage

## S3 method for class 'cov_struct'
format(x, ...)

Arguments

x

(cov_struct)
a covariance structure object.

...

Additional arguments unused.

Value

A formatted string for x.


Format Symbol Objects

Description

For printing, variable names are converted to symbols and deparsed to use R's built-in formatting of variables that may contain spaces or quote characters.

Usage

format_symbols(x)

Arguments

x

(character) A vector of variable names.

Value

A formatted string of comma-separated variables.


Extract Right-Hand-Side (rhs) from Formula

Description

Extract Right-Hand-Side (rhs) from Formula

Usage

formula_rhs(f)

Arguments

f

(formula)
a formula.

Value

A formula without a response, derived from the right-hand-side of the formula, f.

formula_rhs(a ~ b + c)
formula_rhs(~ b + c)

Add Individual Covariance Variables As Terms to Formula

Description

Add Individual Covariance Variables As Terms to Formula

Usage

h_add_covariance_terms(f, covariance)

Arguments

f

(formula)
a formula to which covariance structure terms should be added.

covariance

(cov_struct)
a covariance structure object from which additional variables should be sourced.

Details

stats::update() is used to append the covariance structure and the environment attribute will not be changed. This ensures the returned formula and the input formula have the same environment.

Value

A new formula with included covariance terms.


Add Formula Terms with Character

Description

Add formula terms from the original formula with character representation.

Usage

h_add_terms(f, adds, drop_response = FALSE)

Arguments

f

(formula)
a formula to be updated.

adds

(character)
representation of elements to be added.

drop_response

(flag)
whether response should be dropped.

Details

Elements in adds will be added from the formula, while the environment of the formula is unchanged. If adds is NULL or character(0), the formula is unchanged.

Value

A new formula with elements in drops removed.


Coefficients Table for MMRM Fit

Description

This is used by summary.mmrm() to obtain the coefficients table.

Usage

h_coef_table(object)

Arguments

object

(mmrm)
model fit.

Value

Matrix with one row per coefficient and columns Estimate, ⁠Std. Error⁠, df, ⁠t value⁠ and ⁠Pr(>|t|)⁠.


Ask for Confirmation on Large Visit Levels

Description

Ask the user for confirmation if there are too many visit levels for non-spatial covariance structure in interactive sessions.

Usage

h_confirm_large_levels(x)

Arguments

x

(numeric)
number of visit levels.

Value

Logical value TRUE.


Construction of Model Frame Formula and Data Inputs

Description

Input formulas are converted from mmrm-style to a style compatible with default stats::model.frame() and stats::model.matrix() methods.

The full formula is returned so we can construct, for example, the model.frame() including all columns as well as the requested subset. The full set is used to identify rows to include in the reduced model frame.

Usage

h_construct_model_frame_inputs(
  formula,
  data,
  include,
  include_choice = c("subject_var", "visit_var", "group_var", "response_var"),
  full
)

Arguments

formula

(mmrm)
mmrm fit object.

data

optional data frame that will be passed to model.frame() or model.matrix()

include

(character)
names of variable to include

full

(flag)
indicator whether to return full model frame (deprecated).

Value

named list with four elements:


Default Value on NULL Return default value when first argument is NULL.

Description

Default Value on NULL Return default value when first argument is NULL.

Usage

h_default_value(x, y)

Arguments

x

Object.

y

Object.

Details

If x is NULL, returns y. Otherwise return x.


Calculation of Between-Within Degrees of Freedom for One-Dimensional Contrast

Description

Used in df_1d() if method is "Between-Within".

Usage

h_df_1d_bw(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(numeric)
contrast vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with est, se, df, t_stat and p_val.


Calculation of Kenward-Roger Degrees of Freedom for One-Dimensional Contrast

Description

Used in df_1d() if method is "Kenward-Roger" or "Kenward-Roger-Linear".

Usage

h_df_1d_kr(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(numeric)
contrast vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with est, se, df, t_stat and p_val.


Calculation of Residual Degrees of Freedom for One-Dimensional Contrast

Description

Used in df_1d() if method is "Residual".

Usage

h_df_1d_res(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(numeric)
contrast vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with est, se, df, t_stat and p_val.


Calculation of Satterthwaite Degrees of Freedom for One-Dimensional Contrast

Description

Used in df_1d() if method is "Satterthwaite".

Usage

h_df_1d_sat(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(numeric)
contrast vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with est, se, df, t_stat and p_val.


Helper for Calculation of Satterthwaite with Empirical Covariance Matrix

Description

Used in h_df_1d_sat() and h_df_md_sat() if empirical covariance matrix is used.

Usage

h_df_1d_sat_empirical(object, contrast_matrix)

Arguments

object

(mmrm)
the MMRM fit.

contrast_matrix

(matrix)
contrast matrix with number of subjects times number of coefficients as the number of columns.

Value

Adjusted degrees of freedom value.


Calculation of Between-Within Degrees of Freedom

Description

Used in h_df_1d_bw() and h_df_md_bw().

Usage

h_df_bw_calc(object)

Arguments

object

(mmrm)
the fitted MMRM.

Value

List with:


Calculation of Between-Within Degrees of Freedom for Multi-Dimensional Contrast

Description

Used in df_md() if method is "Between-Within".

Usage

h_df_md_bw(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(matrix)
numeric contrast matrix, if given a numeric then this is coerced to a row vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with num_df, denom_df, f_stat and p_val (2-sided p-value).


Creating F-Statistic Results from One-Dimensional Contrast

Description

Creates multi-dimensional result from one-dimensional contrast from df_1d().

Usage

h_df_md_from_1d(object, contrast)

Arguments

object

(mmrm)
model fit.

contrast

(numeric)
one-dimensional contrast.

Value

The one-dimensional degrees of freedom are calculated and then based on that the p-value is calculated.


Calculation of Kenward-Roger Degrees of Freedom for Multi-Dimensional Contrast

Description

Used in df_md() if method is "Kenward-Roger" or "Kenward-Roger-Linear".

Usage

h_df_md_kr(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(matrix)
numeric contrast matrix, if given a numeric then this is coerced to a row vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with num_df, denom_df, f_stat and p_val (2-sided p-value).


Calculation of Residual Degrees of Freedom for Multi-Dimensional Contrast

Description

Used in df_md() if method is "Residual".

Usage

h_df_md_res(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(matrix)
numeric contrast matrix, if given a numeric then this is coerced to a row vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with num_df, denom_df, f_stat and p_val (2-sided p-value).


Calculation of Satterthwaite Degrees of Freedom for Multi-Dimensional Contrast

Description

Used in df_md() if method is "Satterthwaite".

Usage

h_df_md_sat(object, contrast)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(matrix)
numeric contrast matrix, if given a numeric then this is coerced to a row vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

Value

List with num_df, denom_df, f_stat and p_val (2-sided p-value).


Assign Minimum Degrees of Freedom Given Involved Coefficients

Description

Used in h_df_1d_bw() and h_df_md_bw().

Usage

h_df_min_bw(bw_calc, is_coef_involved)

Arguments

bw_calc

(list)
from h_df_bw_calc().

is_coef_involved

(logical)
whether each coefficient is involved in the contrast.

Value

The minimum of the degrees of freedom assigned to each involved coefficient according to its between-within categorization.


Coerce a Data Frame to a tibble

Description

This is used in h_newdata_add_pred().

Usage

h_df_to_tibble(data)

Arguments

data

(data.frame)
what to coerce.

Details

This is only a thin wrapper around tibble::as_tibble(), except giving a useful error message and it checks for rownames and adds them as a new column .rownames if they are not just a numeric sequence as per the tibble::has_rownames() decision.

Value

The data as a tibble, potentially with a .rownames column.


Drop Formula Terms used for Covariance Structure Definition

Description

Drop Formula Terms used for Covariance Structure Definition

Usage

h_drop_covariance_terms(f)

Arguments

f

(formula)
a formula from which covariance terms should be dropped.

Details

terms is used and it will preserve the environment attribute. This ensures the returned formula and the input formula have the same environment.

Value

The formula without accepted covariance terms.


Drop Levels from Dataset

Description

Drop Levels from Dataset

Usage

h_drop_levels(data, subject_var, visit_var, except)

Arguments

data

(data.frame) data to drop levels.

subject_var

(character) subject variable.

visit_var

(character) visit variable.

except

(character) variables to exclude from dropping.


Check if a Factor Should Drop Levels

Description

Check if a Factor Should Drop Levels

Usage

h_extra_levels(x)

Arguments

x

(vector) vector to check.


Extract Formula Terms used for Covariance Structure Definition

Description

Extract Formula Terms used for Covariance Structure Definition

Usage

h_extract_covariance_terms(f)

Arguments

f

(formula)
a formula from which covariance terms should be extracted.

Value

A list of covariance structure expressions found in f.


Check if the Effect is the First Categorical Effect

Description

Check if the Effect is the First Categorical Effect

Usage

h_first_contain_categorical(effect, factors, categorical)

Arguments

effect

(string) name of the effect.

factors

(matrix) the factor matrix.

categorical

(character) names of the categorical values.


Obtain Contrast for Specified Effect

Description

This is support function to obtain contrast matrix for type II/III testing.

Usage

h_get_contrast(
  object,
  effect,
  type = c("II", "III", "2", "3"),
  tol = sqrt(.Machine$double.eps)
)

Arguments

object

(mmrm)
the fitted MMRM.

effect

(string) the name of the effect.

type

(string) type of test, "II", "III", '2', or '3'.

tol

(numeric) threshold blow which values are treated as 0.

Value

A matrix of the contrast.


Obtain Default Covariance Method

Description

Obtain the default covariance method depending on the degrees of freedom method used.

Usage

h_get_cov_default(
  method = c("Satterthwaite", "Kenward-Roger", "Residual", "Between-Within")
)

Arguments

method

(string)
degrees of freedom method.

Details

The default covariance method is different for different degrees of freedom method. For "Satterthwaite" or "Between-Within", "Asymptotic" is returned. For "Kenward-Roger" only, "Kenward-Roger" is returned. For "Residual" only, "Empirical" is returned.

Value

String of the default covariance method.


Obtain Empirical/Jackknife/Bias-Reduced Covariance

Description

Obtain the empirical or Jackknife covariance for \beta. Used in mmrm fitting if method is "Empirical", "Empirical-Jackknife" or "Empirical-Bias-Reduced".

Usage

h_get_empirical(tmb_data, theta, beta, beta_vcov, type)

Arguments

tmb_data

(mmrm_tmb_data)
produced by h_mmrm_tmb_data().

theta

(numeric)
theta estimate.

beta

(numeric)
beta estimate.

beta_vcov

(matrix)
covariance of beta estimate.

type

(string)
type of empirical method, including "Empirical", "Empirical-Jackknife" and "Empirical-Bias-Reduced".

Value

Named list with elements:

Note

This function used to return df_mat, which was equivalent to crossproduct(g_mat). However, executing the cross product in C++ was a costly matrix multiplication, in particular when the number of coefficients and/or the number of subjects was large. Therefore this is now avoided and g_mat is returned instead.


Test if the First Vector is Subset of the Second Vector

Description

Test if the First Vector is Subset of the Second Vector

Usage

h_get_index(x, y)

Arguments

x

(vector) the first list.

y

(vector) the second list.


Obtain Kenward-Roger Adjustment Components

Description

Obtains the components needed downstream for the computation of Kenward-Roger degrees of freedom. Used in mmrm() fitting if method is "Kenward-Roger".

Usage

h_get_kr_comp(tmb_data, theta)

Arguments

tmb_data

(mmrm_tmb_data)
produced by h_mmrm_tmb_data().

theta

(numeric)
theta estimate.

Details

the function returns a named list, P, Q and R, which corresponds to the paper in 1997. The matrices are stacked in columns so that P, Q and R has the same column number(number of beta parameters). The number of rows, is dependent on the total number of theta and number of groups, if the fit is a grouped mmrm. For P matrix, it is stacked sequentially. For Q and R matrix, it is stacked so that the Q_{ij} and R_{ij} is stacked from j then to i, i.e. R_{i1}, R_{i2}, etc. Q and R only contains intra-group results and inter-group results should be all zero matrices so they are not stacked in the result.

Value

Named list with elements:


Obtain na.action as Function

Description

Obtain na.action as Function

Usage

h_get_na_action(na_action)

Obtain Optimizer according to Optimizer String Value

Description

This function creates optimizer functions with arguments.

Usage

h_get_optimizers(
  optimizer = c("L-BFGS-B", "BFGS", "CG", "nlminb"),
  optimizer_fun = h_optimizer_fun(optimizer),
  optimizer_args = list(),
  optimizer_control = list()
)

Arguments

optimizer

(character)
names of built-in optimizers to try, subset of "L-BFGS-B", "BFGS", "CG" and "nlminb".

optimizer_fun

(function or list of function)
alternatively to optimizer, an optimizer function or a list of optimizer functions can be passed directly here.

optimizer_args

(list)
additional arguments for optimizer_fun.

optimizer_control

(list)
passed to argument control in optimizer_fun.

Details

If you want to use only the built-in optimizers:

If you want to use your own optimizer function:

Value

Named list of optimizers created by h_partial_fun_args().


Get Prediction

Description

Get predictions with given data, theta, beta, beta_vcov.

Usage

h_get_prediction(tmb_data, theta, beta, beta_vcov)

Arguments

tmb_data

(mmrm_tmb_data)
object.

theta

(numeric)
theta value.

beta

(numeric)
beta value.

beta_vcov

(matrix)
beta_vcov matrix.

Details

See predict function in predict.cpp which is called internally.

Value

List with:


Get Prediction Variance

Description

Get prediction variance with given fit, tmb_data with the Monte Carlo sampling method.

Usage

h_get_prediction_variance(object, nsim, tmb_data)

Arguments

object

(mmrm_tmb)
the fitted MMRM.

nsim

(count)
number of samples.

tmb_data

(mmrm_tmb_data)
object.


Get simulated values by patient.

Description

Get simulated values by patient.

Usage

h_get_sim_per_subj(predict_res, nsub, nsim)

Arguments

predict_res

(list)
from h_get_prediction().

nsub

(count)
number of subjects.

nsim

(count)
number of values to simulate.


Obtain Theta from Covariance Matrix

Description

Obtain unstructured theta from covariance matrix.

Usage

h_get_theta_from_cov(covariance)

Arguments

covariance

(matrix) of covariance matrix values.

Details

If the covariance matrix has NA in some of the elements, they will be replaced by 0 (non-diagonal) and 1 (diagonal). This ensures that the matrix is positive definite.

Value

Numeric vector of the theta values.


Computation of a Gradient Given Jacobian and Contrast Vector

Description

Computes the gradient of a linear combination of beta given the Jacobian matrix and variance parameters.

Usage

h_gradient(jac_list, contrast)

Arguments

jac_list

(list)
Jacobian list produced e.g. by h_jac_list().

contrast

(numeric)
contrast vector, which needs to have the same number of elements as there are rows and columns in each element of jac_list.

Value

Numeric vector which contains the quadratic forms of each element of jac_list with the contrast vector.


Obtain List of Jacobian Matrix Entries for Covariance Matrix

Description

Obtain the Jacobian matrices given the covariance function and variance parameters.

Usage

h_jac_list(tmb_data, theta_est, beta_vcov)

Arguments

tmb_data

(mmrm_tmb_data)
produced by h_mmrm_tmb_data().

theta_est

(numeric)
variance parameters point estimate.

beta_vcov

(matrix)
vairance covariance matrix of coefficients.

Value

List with one element per variance parameter containing a matrix of the same dimensions as the covariance matrix. The values are the derivatives with regards to this variance parameter.


Obtain the Adjusted Kenward-Roger degrees of freedom

Description

Obtains the adjusted Kenward-Roger degrees of freedom and F statistic scale parameter. Used in h_df_md_kr() or h_df_1d_kr.

Usage

h_kr_df(v0, l, w, p)

Arguments

v0

(matrix)
unadjusted covariance matrix.

l

(matrix)
linear combination matrix.

w

(matrix)
hessian matrix.

p

(matrix)
P matrix from h_get_kr_comp().

Value

Named list with elements:


Calculating Denominator Degrees of Freedom for the Multi-Dimensional Case

Description

Calculates the degrees of freedom for multi-dimensional contrast.

Usage

h_md_denom_df(t_stat_df)

Arguments

t_stat_df

(numeric)
n t-statistic derived degrees of freedom.

Value

Usually the calculation is returning 2 * E / (E - n) where E is the sum of t / (t - 2) over all t_stat_df values t.

Note

If the input values are two similar to each other then just the average of them is returned. If any of the inputs is not larger than 2 then 2 is returned.


Asserting Sane Start Values for TMB Fit

Description

Asserting Sane Start Values for TMB Fit

Usage

h_mmrm_tmb_assert_start(tmb_object)

Arguments

tmb_object

(list)
created with TMB::MakeADFun().

Value

Nothing, only used for assertions.


Checking the TMB Optimization Result

Description

Checking the TMB Optimization Result

Usage

h_mmrm_tmb_check_conv(tmb_opt, mmrm_tmb)

Arguments

tmb_opt

(list)
optimization result.

mmrm_tmb

(mmrm_tmb)
result from h_mmrm_tmb_fit().

Value

Nothing, only used to generate warnings in case that the model did not converge.


Data for TMB Fit

Description

Data for TMB Fit

Usage

h_mmrm_tmb_data(
  formula_parts,
  data,
  weights,
  reml,
  singular = c("drop", "error", "keep"),
  drop_visit_levels,
  allow_na_response = FALSE,
  drop_levels = TRUE,
  xlev = NULL,
  contrasts = NULL
)

Arguments

formula_parts

(mmrm_tmb_formula_parts)
list with formula parts from h_mmrm_tmb_formula_parts().

data

(data.frame)
which contains variables used in formula_parts.

weights

(vector)
weights to be used in the fitting process.

reml

(flag)
whether restricted maximum likelihood (REML) estimation is used, otherwise maximum likelihood (ML) is used.

singular

(string)
choices of method deal with rank-deficient matrices. "error" to stop the function return the error, "drop" to drop these columns, and "keep" to keep all the columns.

drop_visit_levels

(flag)
whether to drop levels for visit variable, if visit variable is a factor.

allow_na_response

(flag)
whether NA in response is allowed.

drop_levels

(flag)
whether drop levels for covariates. If not dropped could lead to singular matrix.

Details

Note that the subject_var must not be factor but can also be character. If it is character, then it will be converted to factor internally. Here the levels will be the unique values, sorted alphabetically and numerically if there is a common string prefix of numbers in the character elements. For full control on the order please use a factor.

Value

List of class mmrm_tmb_data with elements:


Extract covariance matrix from TMB report and input data

Description

This helper does some simple post-processing to extract covariance matrix or named list of covariance matrices if the fitting is using grouped covariance matrices.

Usage

h_mmrm_tmb_extract_cov(tmb_report, tmb_data, visit_var, is_spatial)

Arguments

tmb_report

(list)
report created with TMB::MakeADFun() report function.

tmb_data

(mmrm_tmb_data)
produced by h_mmrm_tmb_data().

visit_var

(character)
character vector of the visit variable

is_spatial

(flag)
indicator whether the covariance structure is spatial.

Value

Return a simple covariance matrix if there is no grouping, or a named list of estimated grouped covariance matrices, with its name equal to the group levels.


Build TMB Fit Result List

Description

This helper does some simple post-processing of the TMB object and optimization results, including setting names, inverting matrices etc.

Usage

h_mmrm_tmb_fit(tmb_object, tmb_opt, formula_parts, tmb_data)

Arguments

tmb_object

(list)
created with TMB::MakeADFun().

tmb_opt

(list)
optimization result.

formula_parts

(mmrm_tmb_formula_parts)
produced by h_mmrm_tmb_formula_parts().

tmb_data

(mmrm_tmb_data)
produced by h_mmrm_tmb_data().

Details

Instead of inverting or decomposing beta_vcov, it can be more efficient to use its robust Cholesky decomposition LDL^T, therefore we return the corresponding two components L and D as well since they have been available on the ⁠C++⁠ side already.

Value

List of class mmrm_tmb with:


Processing the Formula for TMB Fit

Description

Processing the Formula for TMB Fit

Usage

h_mmrm_tmb_formula_parts(
  formula,
  covariance = as.cov_struct(formula, warn_partial = FALSE)
)

Arguments

formula

(formula)
Original formula.

covariance

(cov_struct)
A covariance structure from which additional formula parts should be added.

Value

List of class mmrm_tmb_formula_parts with elements:


Start Parameters for TMB Fit

Description

Start Parameters for TMB Fit

Usage

h_mmrm_tmb_parameters(formula_parts, tmb_data, start, n_groups = 1L)

Arguments

formula_parts

(mmrm_tmb_formula_parts)
produced by h_mmrm_tmb_formula_parts().

tmb_data

(mmrm_tmb_data)
produced by h_mmrm_tmb_data().

start

(numeric or NULL)
optional start values for variance parameters.

n_groups

(int)
number of groups.

Value

List with element theta containing the start values for the variance parameters.


Add Prediction Results to New Data

Description

This is used in augment.mmrm().

Usage

h_newdata_add_pred(x, newdata, se_fit, interval, ...)

Arguments

x

(mmrm)
fit.

newdata

(data.frame)
data to predict.

se_fit

(flag)
whether to return standard error of prediction, can only be used when interval is not "none".

interval

(string)
type of interval.

...

passed to predict.mmrm_tmb().

Value

The newdata as a tibble with additional columns .fitted, .lower, .upper (if interval is not none) and .se.fit (if se_fit requested).


Obtain Levels Prior and Posterior

Description

Obtain Levels Prior and Posterior

Usage

h_obtain_lvls(var, additional_vars, xlev, factors)

Arguments

var

(string) name of the effect.

additional_vars

(character) names of additional variables.

xlev

(list) named list of character levels.

factors

(matrix) the factor matrix.


Obtain Optimizer Function with Character

Description

Obtain the optimizer function through the character provided.

Usage

h_optimizer_fun(optimizer = c("L-BFGS-B", "BFGS", "CG", "nlminb"))

Arguments

optimizer

(character)
vector of optimizers.

Value

A (list)
of optimizer functions generated from h_partial_fun_args().


Create Partial Functions

Description

Creates partial functions with arguments.

Usage

h_partial_fun_args(fun, ..., additional_attr = list())

Arguments

fun

(function)
to be wrapped.

...

Additional arguments for fun.

additional_attr

(list)
of additional attributes to apply to the result.

Details

This function add args attribute to the original function, and add an extra class partial to the function. args is the argument for the function, and elements in ... will override the existing arguments in attribute args. additional_attr will override the existing attributes.

Value

Object with S3 class "partial", a function with args attribute (and possibly more attributes from additional_attr).


Printing AIC and other Model Fit Criteria

Description

This is used in print.summary.mmrm().

Usage

h_print_aic_list(aic_list, digits = 1)

Arguments

aic_list

(list)
list as part of from summary.mmrm().

digits

(number)
number of decimal places used with round().


Printing MMRM Function Call

Description

This is used in print.summary.mmrm().

Usage

h_print_call(call, n_obs, n_subjects, n_timepoints)

Arguments

call

(call)
original mmrm() function call.

n_obs

(int)
number of observations.

n_subjects

(int)
number of subjects.

n_timepoints

(int)
number of timepoints.


Printing MMRM Covariance Type

Description

This is used in print.summary.mmrm().

Usage

h_print_cov(cov_type, n_theta, n_groups)

Arguments

cov_type

(string)
covariance structure abbreviation.

n_theta

(count)
number of variance parameters.

n_groups

(count)
number of groups.


Quadratic Form Calculations

Description

These helpers are mainly for easier readability and slightly better efficiency of the quadratic forms used in the Satterthwaite calculations.

Usage

h_quad_form_vec(vec, center)

h_quad_form_mat(mat, center)

Arguments

vec

(numeric)
interpreted as a row vector.

center

(matrix)
square numeric matrix with the same dimensions as x as the center of the quadratic form.

mat

(matrix)
numeric matrix to be multiplied left and right of center, therefore needs to have as many columns as there are rows and columns in center.

Functions


Reconcile Possible Covariance Structure Inputs

Description

Reconcile Possible Covariance Structure Inputs

Usage

h_reconcile_cov_struct(formula = NULL, covariance = NULL)

Arguments

formula

(formula)
the model formula, see details.

covariance

(cov_struct)
a covariance structure type definition as produced with cov_struct(), or value that can be coerced to a covariance structure using as.cov_struct(). If no value is provided, a structure is derived from the provided formula.

Value

The value covariance if it's provided or a covariance structure derived from the provided formula otherwise. An error is raised of both are provided.


Capture all Output

Description

This function silences all warnings, errors & messages and instead returns a list containing the results (if it didn't error), as well as the warnings, errors and messages and divergence signals as character vectors.

Usage

h_record_all_output(expr, remove = list(), divergence = list())

Arguments

expr

(expression)
to be executed.

remove

(list)
optional list with elements warnings, errors, messages which can be character vectors, which will be removed from the results if specified.

divergence

(list)
optional list similar as remove, but these character vectors will be moved to the divergence result and signal that the fit did not converge.

Value

A list containing


Register S3 Method Register S3 method to a generic.

Description

Register S3 Method Register S3 method to a generic.

Usage

h_register_s3(pkg, generic, class, envir = parent.frame())

Arguments

pkg

(string) name of the package name.

generic

(string) name of the generic.

class

(string) class name the function want to dispatch.

envir

(environment) the location the method is defined.

Details

This function is adapted from emmeans:::register_s3_method().


Calculate normalized residuals

Description

This is used by residuals.mmrm_tmb() to calculate normalized / scaled residuals.

Usage

h_residuals_normalized(object)

Arguments

object

(mmrm_tmb)
the fitted MMRM.

Value

Vector of residuals


Calculate Pearson Residuals

Description

This is used by residuals.mmrm_tmb() to calculate Pearson residuals.

Usage

h_residuals_pearson(object)

Arguments

object

(mmrm_tmb)
the fitted MMRM.

Value

Vector of residuals.


Calculate response residuals.

Description

This is used by residuals.mmrm_tmb() to calculate response residuals.

Usage

h_residuals_response(object)

Arguments

object

(mmrm_tmb)
the fitted MMRM.

Value

Vector of residuals


Split Control List

Description

Split the mmrm_control() object according to its optimizers and use additional arguments to replace the elements in the original object.

Usage

h_split_control(control, ...)

Arguments

control

(mmrm_control)
object.

...

additional parameters to update the control object.

Value

A list of mmrm_control entries.


Summarizing List of Fits

Description

Summarizing List of Fits

Usage

h_summarize_all_fits(all_fits)

Arguments

all_fits

(list of mmrm_fit or try-error)
list of fits.

Value

List with warnings, messages, log_liks and converged results.


Extract tibble with Confidence Intervals and Term Names

Description

This is used in tidy.mmrm().

Usage

h_tbl_confint_terms(x, ...)

Arguments

x

(mmrm)
fit object.

...

passed to stats::confint(), hence not used at the moment.

Value

A tibble with term, conf.low, conf.high columns.


Creating T-Statistic Test Results For One-Dimensional Contrast

Description

Creates a list of results for one-dimensional contrasts using a t-test statistic and the given degrees of freedom.

Usage

h_test_1d(object, contrast, df)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(numeric)
contrast vector. Note that this should not include elements for singular coefficient estimates, i.e. only refer to the actually estimated coefficients.

df

(number)
degrees of freedom for the one-dimensional contrast.

Value

List with est, se, df, t_stat and p_val (2-sided p-value).


Creating F-Statistic Test Results For Multi-Dimensional Contrast

Description

Creates a list of results for multi-dimensional contrasts using an F-test statistic and the given degrees of freedom.

Usage

h_test_md(object, contrast, df, f_stat_factor = 1)

Arguments

object

(mmrm)
the MMRM fit.

contrast

(matrix)
numeric contrast matrix.

df

(number)
denominator degrees of freedom for the multi-dimensional contrast.

f_stat_factor

(number)
optional scaling factor on top of the standard F-statistic.

Value

List with num_df, denom_df, f_stat and p_val (2-sided p-value).


Predicate if the TMB Version Used to Compile the Package is Sufficient

Description

Predicate if the TMB Version Used to Compile the Package is Sufficient

Usage

h_tmb_version_sufficient()

Value

Flag whether the TMB version is sufficient.


Warn if TMB is Configured to Use Non-Deterministic Hash for Tape Optimizer

Description

This function checks the TMB configuration for the tmbad_deterministic_hash setting If it is set to FALSE, a warning is issued indicating that this may lead to unreproducible results.

Usage

h_tmb_warn_non_deterministic()

Value

No return value, called for side effects.


Trace of a Matrix

Description

Obtain the trace of a matrix if the matrix is diagonal, otherwise raise an error.

Usage

h_tr(x)

Arguments

x

(matrix)
square matrix input.

Value

The trace of the square matrix.


Validate mmrm Formula

Description

Validate mmrm Formula

Usage

h_valid_formula(formula)

Arguments

formula

(formula)
to check.

Details

In mmrm models, . is not allowed as it introduces ambiguity of covariates to be used, so it is not allowed to be in formula.


Obtain the Adjusted Covariance Matrix

Description

Obtains the Kenward-Roger adjusted covariance matrix for the coefficient estimates. Used in mmrm() fitting if method is "Kenward-Roger" or "Kenward-Roger-Linear".

Usage

h_var_adj(v, w, p, q, r, linear = FALSE)

Arguments

v

(matrix)
unadjusted covariance matrix.

w

(matrix)
hessian matrix.

p

(matrix)
P matrix from h_get_kr_comp().

q

(matrix)
Q matrix from h_get_kr_comp().

r

(matrix)
R matrix from h_get_kr_comp().

linear

(flag)
whether to use linear Kenward-Roger approximation.

Value

The matrix of adjusted covariance matrix.


Warn on na.action

Description

Warn on na.action

Usage

h_warn_na_action()

Determine Within or Between for each Design Matrix Column

Description

Used in h_df_bw_calc() to determine whether a variable differs only between subjects or also within subjects.

Usage

h_within_or_between(x_matrix, subject_ids)

Arguments

x_matrix

(matrix)
the design matrix with column names.

subject_ids

(factor)
the subject IDs.

Value

Character vector with "intercept", "within" or "between" for each design matrix column identified via the names of the vector.


Test Whether a Symbol is an Infix Operator

Description

Test Whether a Symbol is an Infix Operator

Usage

is_infix(name)

Arguments

name

(symbol or name or string)
a possible reference to an infix operator to check.

Value

A logical indicating whether the name is the name of an infix operator.

is_infix(as.name("|"))
is_infix("|")
is_infix("c")

Fit an MMRM

Description

[Stable]

This is the main function fitting the MMRM.

Usage

mmrm(
  formula,
  data,
  weights = NULL,
  covariance = NULL,
  reml = TRUE,
  control = mmrm_control(...),
  ...
)

Arguments

formula

(formula)
the model formula, see details.

data

(data)
the data to be used for the model.

weights

(vector)
an optional vector of weights to be used in the fitting process. Should be NULL or a numeric vector.

covariance

(cov_struct)
a covariance structure type definition as produced with cov_struct(), or value that can be coerced to a covariance structure using as.cov_struct(). If no value is provided, a structure is derived from the provided formula.

reml

(flag)
whether restricted maximum likelihood (REML) estimation is used, otherwise maximum likelihood (ML) is used.

control

(mmrm_control)
fine-grained fitting specifications list created with mmrm_control().

...

arguments passed to mmrm_control().

Details

The formula typically looks like: FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID) so specifies response and covariates as usual, and exactly one special term defines which covariance structure is used and what are the time point and subject variables. The covariance structures in the formula can be found in covariance_types.

The time points have to be unique for each subject. That is, there cannot be time points with multiple observations for any subject. The rationale is that these observations would need to be correlated, but it is not possible within the currently implemented covariance structure framework to do that correctly. Moreover, for non-spatial covariance structures, the time variable must be a factor variable.

When optimizer is not set, first the default optimizer (L-BFGS-B) is used to fit the model. If that converges, this is returned. If not, the other available optimizers from h_get_optimizers(), including BFGS, CG and nlminb are tried (in parallel if n_cores is set and not on Windows). If none of the optimizers converge, then the function fails. Otherwise the best fit is returned.

Note that fine-grained control specifications can either be passed directly to the mmrm function, or via the control argument for bundling together with the mmrm_control() function. Both cannot be used together, since this would delete the arguments passed via mmrm.

Value

An mmrm object.

Note

The mmrm object is also an mmrm_fit and an mmrm_tmb object, therefore corresponding methods also work (see mmrm_tmb_methods).

Additional contents depend on vcov (see mmrm_control()):

Note that these additional elements might change over time and are to be considered internal implementation details rather than part of the public user interface of the package.

Use of the package emmeans is supported, see emmeans_support.

NA values are always omitted regardless of na.action setting.

When the number of visit levels is large, it usually requires large memory to create the covariance matrix. By default, the maximum allowed visit levels is 100, and if there are more visit levels, a confirmation is needed if run interactively. You can use ⁠options(mmrm.max_visits = <target>)⁠ to increase the maximum allowed number of visit levels. In non-interactive sessions the confirmation is not raised and will directly give you an error if the number of visit levels exceeds the maximum.

Examples

fit <- mmrm(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data
)

# Direct specification of control details:
fit <- mmrm(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data,
  weights = fev_data$WEIGHTS,
  method = "Kenward-Roger"
)

# Alternative specification via control argument (but you cannot mix the
# two approaches):
fit <- mmrm(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data,
  control = mmrm_control(method = "Kenward-Roger")
)

Control Parameters for Fitting an MMRM

Description

[Stable] Fine-grained specification of the MMRM fit details is possible using this control function.

Usage

mmrm_control(
  n_cores = 1L,
  method = c("Satterthwaite", "Kenward-Roger", "Residual", "Between-Within"),
  vcov = NULL,
  start = std_start,
  accept_singular = TRUE,
  drop_visit_levels = TRUE,
  ...,
  optimizers = h_get_optimizers(...)
)

Arguments

n_cores

(count)
number of cores to be used.

method

(string)
adjustment method for degrees of freedom.

vcov

(string)
coefficients covariance matrix adjustment method.

start

(NULL, numeric or function)
optional start values for variance parameters. See details for more information.

accept_singular

(flag)
whether singular design matrices are reduced to full rank automatically and additional coefficient estimates will be missing.

drop_visit_levels

(flag)
whether to drop levels for visit variable, if visit variable is a factor, see details.

...

additional arguments passed to h_get_optimizers().

optimizers

(list)
optimizer specification, created with h_get_optimizers().

Details

For example, if the data only has observations at visits VIS1, VIS3 and VIS4, by default they are treated to be equally spaced, the distance from VIS1 to VIS3, and from VIS3 to VIS4, are identical. However, you can manually convert this visit into a factor, with levels = c("VIS1", "VIS2", "VIS3", "VIS4"), and also use drop_visits_levels = FALSE, then the distance from VIS1 to VIS3 will be double, as VIS2 is a valid visit. However, please be cautious because this can lead to convergence failure when using an unstructured covariance matrix and there are no observations at the missing visits.

Value

List of class mmrm_control with the control parameters.

Examples

mmrm_control(
  optimizer_fun = stats::optim,
  optimizer_args = list(method = "L-BFGS-B")
)

Methods for mmrm Objects

Description

[Stable]

Usage

## S3 method for class 'mmrm'
summary(object, ...)

## S3 method for class 'summary.mmrm'
print(
  x,
  digits = max(3, getOption("digits") - 3),
  signif.stars = getOption("show.signif.stars"),
  ...
)

## S3 method for class 'mmrm'
confint(object, parm, level = 0.95, ...)

Arguments

object

(mmrm)
the fitted MMRM including Jacobian and call etc.

...

not used.

Details

While printing the summary of (mmrm)
object, the following will be displayed:

  1. Formula. The formula used in the model.

  2. Data. The data used for analysis, including number of subjects, number of valid observations.

  3. Covariance. The covariance structure and number of variance parameters.

  4. Method. Restricted maximum likelihood(REML) or maximum likelihood(ML).

  5. Model selection criteria. AIC, BIC, log likelihood and deviance.

  6. Coefficients. Coefficients of the covariates.

  7. Covariance estimate. The covariance estimate(for each group).

    1. If the covariance structure is non-spatial, the covariance matrix of all categorical time points available in data will be displayed.

    2. If the covariance structure is spatial, the covariance matrix of two time points with unit distance will be displayed.

confint is used to obtain the confidence intervals for the coefficients. Please note that this is different from the confidence interval of difference of least square means from emmeans.

Value

Depends on the method, see Details and Functions.

Functions

See Also

mmrm_tmb_methods, mmrm_tidiers for additional methods.

Examples

formula <- FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID)
object <- mmrm(formula, fev_data)
# Summary:
summary(object)
# Confidence Interval:
confint(object)

Tidying Methods for mmrm Objects

Description

[Stable]

These methods tidy the estimates from an mmrm object into a summary.

Usage

## S3 method for class 'mmrm'
tidy(x, conf.int = FALSE, conf.level = 0.95, ...)

## S3 method for class 'mmrm'
glance(x, ...)

## S3 method for class 'mmrm'
augment(
  x,
  newdata = NULL,
  interval = c("none", "confidence", "prediction"),
  se_fit = (interval != "none"),
  type.residuals = c("response", "pearson", "normalized"),
  ...
)

Arguments

x

(mmrm)
fitted model.

conf.int

(flag)
if TRUE columns for the lower (conf.low) and upper bounds (conf.high) of coefficient estimates are included.

conf.level

(number)
defines the range of the optional confidence internal.

...

only used by augment() to pass arguments to the predict.mmrm_tmb() method.

newdata

(data.frame or NULL)
optional new data frame.

interval

(string)
type of interval calculation.

se_fit

(flag)
whether to return standard errors of fit.

type.residuals

(string)
passed on to residuals.mmrm_tmb().

Functions

See Also

mmrm_methods, mmrm_tmb_methods for additional methods.

Examples

fit <- mmrm(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data
)
# Applying tidy method to return summary table of covariate estimates.
fit |> tidy()
fit |> tidy(conf.int = TRUE, conf.level = 0.9)
# Applying glance method to return summary table of goodness of fit statistics.
fit |> glance()
# Applying augment method to return merged `tibble` of model data, fitted and residuals.
fit |> augment()
fit |> augment(interval = "confidence")
fit |> augment(type.residuals = "pearson")

Methods for mmrm_tmb Objects

Description

[Stable]

Usage

## S3 method for class 'mmrm_tmb'
coef(object, complete = TRUE, ...)

## S3 method for class 'mmrm_tmb'
fitted(object, ...)

## S3 method for class 'mmrm_tmb'
predict(
  object,
  newdata,
  se.fit = FALSE,
  interval = c("none", "confidence", "prediction"),
  level = 0.95,
  nsim = 1000L,
  conditional = FALSE,
  ...
)

## S3 method for class 'mmrm_tmb'
model.frame(
  formula,
  data,
  include = c("subject_var", "visit_var", "group_var", "response_var"),
  full,
  na.action = "na.omit",
  ...
)

## S3 method for class 'mmrm_tmb'
model.matrix(object, data, use_response = TRUE, ...)

## S3 method for class 'mmrm_tmb'
terms(x, include = "response_var", ...)

## S3 method for class 'mmrm_tmb'
logLik(object, ...)

## S3 method for class 'mmrm_tmb'
formula(x, ...)

## S3 method for class 'mmrm_tmb'
vcov(object, complete = TRUE, ...)

## S3 method for class 'mmrm_tmb'
VarCorr(x, sigma = NA, ...)

## S3 method for class 'mmrm_tmb'
deviance(object, ...)

## S3 method for class 'mmrm_tmb'
AIC(object, corrected = FALSE, ..., k = 2)

## S3 method for class 'mmrm_tmb'
BIC(object, ...)

## S3 method for class 'mmrm_tmb'
print(x, ...)

## S3 method for class 'mmrm_tmb'
residuals(object, type = c("response", "pearson", "normalized"), ...)

## S3 method for class 'mmrm_tmb'
simulate(
  object,
  nsim = 1,
  seed = NULL,
  newdata,
  ...,
  method = c("conditional", "marginal")
)

Arguments

object

(mmrm_tmb)
the fitted MMRM object.

complete

(flag)
whether to include potential non-estimable coefficients.

...

mostly not used; Exception is model.matrix() passing ... to the default method.

newdata

(data.frame)
optional new data, otherwise data from object is used.

se.fit

(flag)
indicator if standard errors are required.

interval

(string)
type of interval calculation. Can be abbreviated.

level

(number)
tolerance/confidence level.

nsim

(count)
number of simulations to use.

conditional

(flag)
indicator if the prediction is conditional on the observation or not.

formula

(mmrm_tmb)
same as object.

data

(data.frame)
object in which to construct the frame.

include

(character)
names of variable types to include. Must be NULL or one or more of c("subject_var", "visit_var", "group_var", "response_var").

full

(flag)
indicator whether to return full model frame (deprecated).

na.action

(string)
na action.

use_response

(flag)
whether to use the response for complete rows.

x

(mmrm_tmb)
same as object.

sigma

cannot be used (this parameter does not exist in MMRM).

corrected

(flag)
whether corrected AIC should be calculated.

k

(number)
the penalty per parameter to be used; default k = 2 is the classical AIC.

type

(string)
unscaled (response), pearson or normalized. Default is response, and this is the only type available for use with models with a spatial covariance structure.

seed

unused argument from stats::simulate().

method

(string)
simulation method to use. If "conditional", simulated values are sampled given the estimated covariance matrix of object. If "marginal", the variance of the estimated covariance matrix is taken into account.

Details

include argument controls the variables the returned model frame will include. Possible options are "response_var", "subject_var", "visit_var" and "group_var", representing the response variable, subject variable, visit variable or group variable. character values in new data will always be factorized according to the data in the fit to avoid mismatched in levels or issues in model.matrix.

Value

Depends on the method, see Functions.

Functions

References

See Also

mmrm_methods, mmrm_tidiers for additional methods.

Examples

formula <- FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID)
object <- fit_mmrm(formula, fev_data, weights = rep(1, nrow(fev_data)))
# Estimated coefficients:
coef(object)
# Fitted values:
fitted(object)
predict(object, newdata = fev_data)
# Model frame:
model.frame(object)
model.frame(object, include = "subject_var")
# Model matrix:
model.matrix(object)
# terms:
terms(object)
terms(object, include = "subject_var")
# Log likelihood given the estimated parameters:
logLik(object)
# Formula which was used:
formula(object)
# Variance-covariance matrix estimate for coefficients:
vcov(object)
# Variance-covariance matrix estimate for residuals:
VarCorr(object)
# REML criterion (twice the negative log likelihood):
deviance(object)
# AIC:
AIC(object)
AIC(object, corrected = TRUE)
# BIC:
BIC(object)
# residuals:
residuals(object, type = "response")
residuals(object, type = "pearson")
residuals(object, type = "normalized")

Register mmrm For Use With tidymodels

Description

Register mmrm For Use With tidymodels

Usage

parsnip_add_mmrm(quietly = FALSE)

Arguments

quietly

logical: should progress and error messages be suppressed?

Details

We can use parsnip::show_model_info("linear_reg") to check the registration with parsnip and thus the wider tidymodels ecosystem.

Value

A logical value indicating whether registration was successful.


Search For the Position of a Symbol

Description

A thin wrapper around base::Position() to search through a list of language objects, as produced by flatten_call() or flatten_expr(), for the presence of a specific symbol.

Usage

position_symbol(x, sym, ...)

Arguments

x

(list of language)
a list of language objects in which to search for a specific symbol.

sym

(name or symbol or character)
a symbol to search for in x.

...

Additional arguments passed to Position().

Value

The position of the symbol if found, or the nomatch value otherwise.


Print a Covariance Structure Object

Description

Print a Covariance Structure Object

Usage

## S3 method for class 'cov_struct'
print(x, ...)

Arguments

x

(cov_struct)
a covariance structure object.

...

Additional arguments unused.

Value

x invisibly.


Objects exported from other packages

Description

These objects are imported from other packages. Follow the links below to see their documentation.

generics

augment, glance, tidy


Refitting MMRM with Multiple Optimizers

Description

[Stable]

Usage

refit_multiple_optimizers(fit, ..., control = mmrm_control(...))

Arguments

fit

(mmrm_fit)
original model fit from fit_single_optimizer().

...

Additional arguments passed to mmrm_control().

control

(mmrm_control)
object.

Value

The best (in terms of log likelihood) fit which converged.

Note

For Windows, no parallel computations are currently implemented.

Examples

fit <- fit_single_optimizer(
  formula = FEV1 ~ RACE + SEX + ARMCD * AVISIT + us(AVISIT | USUBJID),
  data = fev_data,
  weights = rep(1, nrow(fev_data)),
  optimizer = "nlminb"
)
best_fit <- refit_multiple_optimizers(fit)

Helper Function for Registering Functionality With Suggests Packages

Description

Helper Function for Registering Functionality With Suggests Packages

Usage

register_on_load(
  pkg,
  ver = c(NA_character_, NA_character_),
  callback,
  message = NULL
)

Arguments

pkg

(string)
package name.

ver

(character)
of length 2 whose elements can be provided to numeric_version(), representing a minimum and maximum (inclusive) version requirement for interoperability. When NA, no version requirement is imposed. Defaults to no version requirement.

callback

(function(...) ANY)
a callback to execute upon package load. Note that no arguments are passed to this function. Any necessary data must be provided upon construction.

message

(NULL or string)
an optional message to print after the callback is executed upon successful registration.

Value

A logical (invisibly) indicating whether registration was successful. If not, a onLoad hook was set for the next time the package is loaded.


Standard Starting Value

Description

Obtain standard start values.

Usage

std_start(cov_type, n_visits, n_groups, ...)

Arguments

cov_type

(string)
name of the covariance structure.

n_visits

(int)
number of visits.

n_groups

(int)
number of groups.

...

not used.

Details

std_start will try to provide variance parameter from identity matrix. However, for ar1 and ar1h the corresponding values are not ideal because the \rho is usually a positive number thus using 0 as starting value can lead to incorrect optimization result, and we use 0.5 as the initial value of \rho.

Value

A numeric vector of starting values.


Produce A Covariance Identifier Passing to TMB

Description

Produce A Covariance Identifier Passing to TMB

Usage

tmb_cov_type(cov)

Arguments

cov

(cov_struct)
a covariance structure object.

Value

A string used for method dispatch when passed to TMB.


Validate Covariance Structure Data

Description

Run checks against relational integrity of covariance definition

Usage

validate_cov_struct(x)

Arguments

x

(cov_struct)
a covariance structure object.

Value

x if successful, or an error is thrown otherwise.

mirror server hosted at Truenetwork, Russian Federation.