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
|
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:
Liming Li liming.li1@astrazeneca.com (ORCID)
Julia Dedic julia.dedic@roche.com
Doug Kelkhoff doug.kelkhoff@roche.com
Kevin Kunzmann kevin.kunzmann@boehringer-ingelheim.com
Brian Matthew Lang brian.lang@msd.com
Christian Stock christian.stock@boehringer-ingelheim.com
Ya Wang ya.wang10@gilead.com
Dan James dan.james@astrazeneca.com
Jonathan Sidi yoni@pinpointstrategies.io
Daniel Leibovitz daniel.leibovitz@roche.com
Daniel D. Sjoberg sjobergd@gene.com (ORCID)
Nikolas Ivan Krieger nikolas.krieger@experis.com (ORCID)
Other contributors:
Craig Gower-Page craig.gower-page@roche.com [contributor]
Lukas A. Widmer (ORCID) [contributor]
Boehringer Ingelheim Ltd. [copyright holder, funder]
Gilead Sciences, Inc. [copyright holder, funder]
F. Hoffmann-La Roche AG [copyright holder, funder]
Merck Sharp & Dohme, Inc. [copyright holder, funder]
AstraZeneca plc [copyright holder, funder]
inferential.biostatistics GmbH [copyright holder, funder]
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 |
( |
type |
( |
tol |
( |
... |
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 orNA
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
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 |
( |
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)
-
as.cov_struct(formula)
: When provided a formula, any specialized functions are assumed to be covariance structure definitions and must follow the form:y ~ xs + type( (visit, )* visit | (group /)? subject )
Any component on the right hand side of a formula is considered when searching for a covariance definition.
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
Usage
bcva_data
Format
A tibble
with 10,000 rows and 7 variables:
-
USUBJID
: subject ID. -
VISITN
: visit number (numeric). -
AVISIT
: visit number (factor). -
ARMCD
: treatment,TRT
orCTL
. -
RACE
: 3-category race. -
BCVA_BL
: BCVA at baseline. -
BCVA_CHG
: Change in BCVA at study visits.
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
Usage
cached_mmrm_results
Format
A list
with following elements:
-
conv_time_fev
: Convergence time on FEV data. -
conv_time_bcva
: Convergence time on BCVA data. -
rel_diff_ests_tbl_fev
: Relative difference in estimates on FEV data. -
rel_diff_ests_tbl_bcva
: Relative difference in estimates on BCVA data. -
conv_rate
: Convergence rate on data with different missing levels. -
df_missingness
: Summary of missingness on simulated data.
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 |
( |
ver |
( |
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
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 |
( |
name |
( |
Details
Available component()
names are as follows:
-
call
: low-level function call which generated the model. -
formula
: model formula. -
dataset
: data set name. -
cov_type
: covariance structure type. -
n_theta
: number of parameters. -
n_subjects
: number of subjects. -
n_timepoints
: number of modeled time points. -
n_obs
: total number of observations. -
reml
: was REML used (ML was used ifFALSE
). -
neg_log_lik
: negative log likelihood. -
convergence
: convergence code from optimizer. -
conv_message
: message accompanying the convergence code. -
evaluations
: number of function evaluations for optimization. -
method
: Adjustment method which was used (formmrm
objects), otherwiseNULL
(formmrm_tmb
objects). -
beta_vcov
: estimated variance-covariance matrix of coefficients (excluding aliased coefficients). When Kenward-Roger/Empirical adjusted coefficients covariance matrix is used, the adjusted covariance matrix is returned (to still obtain the original asymptotic covariance matrix useobject$beta_vcov
). -
beta_vcov_complete
: estimated variance-covariance matrix including aliased coefficients with entries set toNA
. -
varcor
: estimated covariance matrix for residuals. If there are multiple groups, a named list of estimated covariance matrices for residuals will be returned. The names are the group levels. -
score_per_subject
: score per subject in empirical covariance. See the vignettevignette("coef_vcov", package = "mmrm")
. -
theta_est
: estimated variance parameters. -
beta_est
: estimated coefficients (excluding aliased coefficients). -
beta_est_complete
: estimated coefficients including aliased coefficients set toNA
. -
beta_aliased
: whether each coefficient was aliased (i.e. cannot be estimated) or not. -
theta_vcov
: estimated variance-covariance matrix of variance parameters. -
x_matrix
: design matrix used (excluding aliased columns). -
xlev
: a named list of character vectors giving the full set of levels to be assumed for each factor. -
contrasts
: a list of contrasts used for each factor. -
y_vector
: response vector used. -
jac_list
: Jacobian, seeh_jac_list()
for details. -
full_frame
:data.frame
withn
rows containing all variables needed in the model.
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
Usage
cov_struct(
type = cov_types(),
visits,
subject,
group = character(),
heterogeneous = FALSE
)
Arguments
type |
( |
visits |
( |
subject |
( |
group |
( |
heterogeneous |
( |
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 |
( |
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 |
( |
Value
The corresponding abbreviated covariance type name.
Covariance Types
Description
Usage
cov_types(
form = c("name", "abbr", "habbr"),
filter = c("heterogeneous", "spatial")
)
Arguments
form |
( |
filter |
( |
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
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 |
( |
contrast |
( |
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
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 |
( |
contrast |
( |
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 |
n |
( |
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
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 |
( |
model_formula |
( |
visit_var |
( |
subject_var |
( |
subject_groups |
( |
... |
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
Usage
fev_data
Format
A tibble
with 800 rows and 7 variables:
-
USUBJID
: subject ID. -
AVISIT
: visit number. -
ARMCD
: treatment,TRT
orPBO
. -
RACE
: 3-category race. -
SEX
: sex. -
FEV1_BL
: FEV1 at baseline (%). -
FEV1
: FEV1 at study visits. -
WEIGHT
: weighting variable. -
VISITN
: integer order of the visit. -
VISITN2
: coordinates of the visit for distance calculation.
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 |
( |
Value
A named vector or list.
Low-Level Fitting Function for MMRM
Description
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 |
( |
data |
( |
weights |
( |
reml |
( |
covariance |
( |
tmb_data |
( |
formula_parts |
( |
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
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 |
( |
data |
( |
weights |
( |
reml |
( |
covariance |
( |
tmb_data |
( |
formula_parts |
( |
... |
Additional arguments to pass to |
control |
( |
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 |
( |
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
-
flatten_call()
: Flatten a call into a list of names and argument expressions.The call name and all arguments are flattened into the same list, meaning a call of the form
sp_exp(a, b, c | d / e)
produces a list of the form(sp_exp, a, b, c, |, d, /, e)
.flatten_call(quote(sp_exp(a, b, c | d / e)))
-
flatten_expr()
: Flatten nested expressionsflatten_expr(quote(1 + 2 + 3 | 4))
Format Covariance Structure Object
Description
Format Covariance Structure Object
Usage
## S3 method for class 'cov_struct'
format(x, ...)
Arguments
x |
( |
... |
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 |
( |
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 |
( |
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 |
( |
covariance |
( |
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 |
( |
adds |
( |
drop_response |
( |
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 |
( |
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 |
( |
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 |
( |
data |
optional data frame that will be
passed to |
include |
( |
full |
( |
Value
named list with four elements:
-
"formula"
: the formula including the columns requested in theinclude=
argument. -
"data"
: a data frame including all columns needed in the formula. full formula are identical
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 |
( |
contrast |
( |
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 |
( |
contrast |
( |
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 |
( |
contrast |
( |
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 |
( |
contrast |
( |
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 |
( |
contrast_matrix |
( |
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 |
( |
Value
List with:
-
coefs_between_within
calculated viah_within_or_between()
-
ddf_between
-
ddf_within
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 |
( |
contrast |
( |
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 |
( |
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 |
( |
contrast |
( |
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 |
( |
contrast |
( |
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 |
( |
contrast |
( |
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 |
( |
is_coef_involved |
( |
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 |
( |
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 |
( |
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 |
( |
subject_var |
( |
visit_var |
( |
except |
( |
Check if a Factor Should Drop Levels
Description
Check if a Factor Should Drop Levels
Usage
h_extra_levels(x)
Arguments
x |
( |
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 |
( |
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 |
( |
factors |
( |
categorical |
( |
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 |
( |
effect |
( |
type |
( |
tol |
( |
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 |
( |
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 |
( |
theta |
( |
beta |
( |
beta_vcov |
( |
type |
( |
Value
Named list with elements:
-
cov
:matrix
empirical covariance. -
g_mat
:matrix
to calculate Satterthwaite degrees of freedom.
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 |
( |
y |
( |
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 |
( |
theta |
( |
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:
-
P
:matrix
ofP
component. -
Q
:matrix
ofQ
component. -
R
:matrix
ofR
component.
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 |
( |
optimizer_fun |
( |
optimizer_args |
( |
optimizer_control |
( |
Details
If you want to use only the built-in optimizers:
-
optimizer
is a shortcut to create a list of built-in optimizer functions passed tooptimizer_fun
. Allowed are "L-BFGS-B", "BFGS", "CG" (using
stats::optim()
with corresponding method) and "nlminb" (usingstats::nlminb()
).Other arguments should go into
optimizer_args
.
If you want to use your own optimizer function:
Make sure that there are three arguments: parameter (start value), objective function and gradient function are sequentially in the function arguments.
If there are other named arguments in front of these, make sure they are correctly specified through
optimizer_args
.If the hessian can be used, please make sure its argument name is
hessian
and please add attributeuse_hessian = TRUE
to the function, usingattr(fun, "use_hessian) <- TRUE
.
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 |
( |
theta |
( |
beta |
( |
beta_vcov |
( |
Details
See predict
function in predict.cpp
which is called internally.
Value
List with:
-
prediction
: Matrix with columnsfit
,conf_var
, andvar
. -
covariance
: List with subject specific covariance matrices. -
index
: List of zero-based subject indices.
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 |
( |
nsim |
( |
tmb_data |
( |
Get simulated values by patient.
Description
Get simulated values by patient.
Usage
h_get_sim_per_subj(predict_res, nsub, nsim)
Arguments
predict_res |
( |
nsub |
( |
nsim |
( |
Obtain Theta from Covariance Matrix
Description
Obtain unstructured theta from covariance matrix.
Usage
h_get_theta_from_cov(covariance)
Arguments
covariance |
( |
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 |
( |
contrast |
( |
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 |
( |
theta_est |
( |
beta_vcov |
( |
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 |
( |
l |
( |
w |
( |
p |
( |
Value
Named list with elements:
-
m
:numeric
degrees of freedom. -
lambda
:numeric
F statistic scale parameter.
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 |
( |
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 |
( |
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 |
( |
mmrm_tmb |
( |
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 |
( |
data |
( |
weights |
( |
reml |
( |
singular |
( |
drop_visit_levels |
( |
allow_na_response |
( |
drop_levels |
( |
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:
-
full_frame
:data.frame
withn
rows containing all variables needed in the model. -
data
:data.frame
of input dataset. -
x_matrix
:matrix
withn
rows andp
columns specifying the overall design matrix. -
x_cols_aliased
:logical
with potentially more thanp
elements indicating which columns in the original design matrix have been left out to obtain a full rankx_matrix
. -
y_vector
: lengthn
numeric
specifying the overall response vector. -
weights_vector
: lengthn
numeric
specifying the weights vector. -
n_visits
:int
with the number of visits, which is the dimension of the covariance matrix. -
n_subjects
:int
with the number of subjects. -
subject_zero_inds
: lengthn_subjects
integer
containing the zero-based start indices for each subject. -
subject_n_visits
: lengthn_subjects
integer
containing the number of observed visits for each subjects. So the sum of this vector equalsn
. -
cov_type
:string
value specifying the covariance type. -
is_spatial_int
:int
specifying whether the covariance structure is spatial(1) or not(0). -
reml
:int
specifying whether REML estimation is used (1), otherwise ML (0). -
subject_groups
:factor
specifying the grouping for each subject. -
n_groups
:int
with the number of total groups
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 |
( |
tmb_data |
( |
visit_var |
( |
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 |
( |
tmb_opt |
( |
formula_parts |
( |
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:
-
cov
: estimated covariance matrix, or named list of estimated group specific covariance matrices. -
beta_est
: vector of coefficient estimates. -
beta_vcov
: Variance-covariance matrix for coefficient estimates. -
beta_vcov_inv_L
: Lower triangular matrixL
of the inverse variance-covariance matrix decomposition. -
beta_vcov_inv_D
: vector of diagonal matrixD
of the inverse variance-covariance matrix decomposition. -
theta_est
: vector of variance parameter estimates. -
theta_vcov
: variance-covariance matrix for variance parameter estimates. -
neg_log_lik
: obtained negative log-likelihood. -
formula_parts
: input. -
data
: input. -
weights
: input. -
reml
: input as a flag. -
opt_details
: list with optimization details including convergence code. -
tmb_object
: originalTMB
object created withTMB::MakeADFun()
. -
tmb_data
: input.
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 |
( |
covariance |
( |
Value
List of class mmrm_tmb_formula_parts
with elements:
-
formula
: the original input. -
model_formula
:formula
with the covariance term is removed. -
model_formula
:formula
with the covariance term removed. -
full_formula
: same asmodel_formula
but includes the covariance structure's subject, visit and (optionally) group variables. -
cov_type
:string
with covariance term type (e.g."us"
). -
is_spatial
:flag
indicator of whether the covariance structure is spatial -
visit_var
:character
with the visit variable name. -
subject_var
:string
with the subject variable name. -
group_var
:string
with the group variable name. If no group specified, this element isNULL
. -
model_var
:character
with the variables names of the formula, exceptsubject_var
.
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 |
( |
tmb_data |
( |
start |
( |
n_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 |
( |
newdata |
( |
se_fit |
( |
interval |
( |
... |
passed to |
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 |
( |
additional_vars |
( |
xlev |
( |
factors |
( |
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 |
( |
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 |
( |
... |
Additional arguments for |
additional_attr |
( |
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 |
( |
digits |
( |
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 |
( |
n_obs |
( |
n_subjects |
( |
n_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 |
( |
n_theta |
( |
n_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 |
( |
center |
( |
mat |
( |
Functions
-
h_quad_form_vec()
: calculates the numbervec %*% center %*% t(vec)
as a numeric (not a matrix). -
h_quad_form_mat()
: calculates the quadratic formmat %*% center %*% t(mat)
as a matrix, the result is square and has dimensions identical to the number of rows inmat
.
Reconcile Possible Covariance Structure Inputs
Description
Reconcile Possible Covariance Structure Inputs
Usage
h_reconcile_cov_struct(formula = NULL, covariance = NULL)
Arguments
formula |
( |
covariance |
( |
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 |
( |
remove |
( |
divergence |
( |
Value
A list containing
-
result
: The object returned byexpr
orlist()
if an error was thrown. -
warnings
:NULL
or a character vector if warnings were thrown. -
errors
:NULL
or a string if an error was thrown. -
messages
:NULL
or a character vector if messages were produced. -
divergence
:NULL
or a character vector if divergence messages were caught.
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 |
( |
generic |
( |
class |
( |
envir |
( |
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 |
( |
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 |
( |
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 |
( |
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 |
( |
... |
additional parameters to update the |
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 |
( |
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 |
( |
... |
passed to |
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 |
( |
contrast |
( |
df |
( |
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 |
( |
contrast |
( |
df |
( |
f_stat_factor |
( |
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 |
( |
Value
The trace of the square matrix.
Validate mmrm Formula
Description
Validate mmrm Formula
Usage
h_valid_formula(formula)
Arguments
formula |
( |
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 |
( |
w |
( |
p |
( |
q |
( |
r |
( |
linear |
( |
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 |
( |
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 |
( |
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
This is the main function fitting the MMRM.
Usage
mmrm(
formula,
data,
weights = NULL,
covariance = NULL,
reml = TRUE,
control = mmrm_control(...),
...
)
Arguments
formula |
( |
data |
( |
weights |
( |
covariance |
( |
reml |
( |
control |
( |
... |
arguments passed to |
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()
):
If Kenward-Roger covariance matrix is used,
kr_comp
contains necessary components andbeta_vcov_adj
includes the adjusted coefficients covariance matrix.If Empirical covariance matrix is used,
beta_vcov_adj
contains the corresponding coefficients covariance matrix estimate. In addition,empirical_g_mat
contains the empirical g matrix, which is used to calculate the Satterthwaite degrees of freedom. Thescore_per_subject
contains the empirical score per subject.If Asymptotic covariance matrix is used in combination with Satterthwaite d.f. adjustment, the Jacobian information
jac_list
is included.
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
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 |
( |
method |
( |
vcov |
( |
start |
( |
accept_singular |
( |
drop_visit_levels |
( |
... |
additional arguments passed to |
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.
The
method
andvcov
arguments specify the degrees of freedom and coefficients covariance matrix adjustment methods, respectively.Allowed
vcov
includes: "Asymptotic", "Kenward-Roger", "Kenward-Roger-Linear", "Empirical" (CR0), "Empirical-Jackknife" (CR3), and "Empirical-Bias-Reduced" (CR2).Allowed
method
includes: "Satterthwaite", "Kenward-Roger", "Between-Within" and "Residual".If
method
is "Kenward-Roger" then only "Kenward-Roger" or "Kenward-Roger-Linear" are allowed forvcov
.
The
vcov
argument can beNULL
to use the default covariance method depending on themethod
used for degrees of freedom, see the following table:method
Default vcov
Satterthwaite Asymptotic Kenward-Roger Kenward-Roger Residual Empirical Between-Within Asymptotic Please note that "Kenward-Roger" for "Unstructured" covariance gives different results compared to SAS; Use "Kenward-Roger-Linear" for
vcov
instead for better matching of the SAS results.The argument
start
is used to facilitate the choice of initial values for fitting the model. Iffunction
is provided, make sure its parameter is a valid element ofmmrm_tmb_data
ormmrm_tmb_formula_parts
and it returns a numeric vector. By default or ifNULL
is provided,std_start
will be used. Other implemented methods includeemp_start
.
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
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 |
( |
... |
not used. |
Details
While printing the summary of (mmrm
)
object, the following will be displayed:
Formula. The formula used in the model.
Data. The data used for analysis, including number of subjects, number of valid observations.
Covariance. The covariance structure and number of variance parameters.
Method. Restricted maximum likelihood(REML) or maximum likelihood(ML).
Model selection criteria. AIC, BIC, log likelihood and deviance.
Coefficients. Coefficients of the covariates.
Covariance estimate. The covariance estimate(for each group).
If the covariance structure is non-spatial, the covariance matrix of all categorical time points available in data will be displayed.
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
-
summary(mmrm)
: summarizes the MMRM fit results. -
print(summary.mmrm)
: prints the MMRM fit summary. -
confint(mmrm)
: obtain the confidence intervals for the coefficients.
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
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 |
( |
conf.int |
( |
conf.level |
( |
... |
only used by |
newdata |
( |
interval |
( |
se_fit |
( |
type.residuals |
( |
Functions
-
tidy(mmrm)
: derives tidytibble
from anmmrm
object. -
glance(mmrm)
: derivesglance
tibble
from anmmrm
object. -
augment(mmrm)
: derivesaugment
tibble
from anmmrm
object.
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
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 |
( |
complete |
( |
... |
mostly not used;
Exception is |
newdata |
( |
se.fit |
( |
interval |
( |
level |
( |
nsim |
( |
conditional |
( |
formula |
( |
data |
( |
include |
( |
full |
( |
na.action |
( |
use_response |
( |
x |
( |
sigma |
cannot be used (this parameter does not exist in MMRM). |
corrected |
( |
k |
( |
type |
( |
seed |
unused argument from |
method |
( |
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
-
coef(mmrm_tmb)
: obtains the estimated coefficients. -
fitted(mmrm_tmb)
: obtains the fitted values. -
predict(mmrm_tmb)
: predict conditional means for new data; optionally with standard errors and confidence or prediction intervals. Returns a vector of predictions ifse.fit == FALSE
andinterval == "none"
; otherwise it returns a data.frame with multiple columns and one row per input data row. -
model.frame(mmrm_tmb)
: obtains the model frame. -
model.matrix(mmrm_tmb)
: obtains the model matrix. -
terms(mmrm_tmb)
: obtains the terms object. -
logLik(mmrm_tmb)
: obtains the attained log likelihood value. -
formula(mmrm_tmb)
: obtains the used formula. -
vcov(mmrm_tmb)
: obtains the variance-covariance matrix estimate for the coefficients. -
VarCorr(mmrm_tmb)
: obtains the variance-covariance matrix estimate for the residuals. -
deviance(mmrm_tmb)
: obtains the deviance, which is defined here as twice the negative log likelihood, which can either be integrated over the coefficients for REML fits or the usual one for ML fits. -
AIC(mmrm_tmb)
: obtains the Akaike Information Criterion, where the degrees of freedom are the number of variance parameters (n_theta
). Ifcorrected
, then this is multiplied withm / (m - n_theta - 1)
wherem
is the number of observations minus the number of coefficients, orn_theta + 2
if it is smaller than that (Hurvich and Tsai 1989; Burnham and Anderson 1998). -
BIC(mmrm_tmb)
: obtains the Bayesian Information Criterion, which is using the natural logarithm of the number of subjects for the penalty parameterk
. -
print(mmrm_tmb)
: prints the object. -
residuals(mmrm_tmb)
: to obtain residuals - either unscaled ('response'), 'pearson' or 'normalized'. -
simulate(mmrm_tmb)
: simulate responses from a fitted model according to the simulationmethod
, returning adata.frame
of dimension[n, m]
where n is the number of rows innewdata
, and m is the numbernsim
of simulated responses.
References
-
Hurvich CM, Tsai C (1989). “Regression and time series model selection in small samples.” Biometrika, 76(2), 297–307. doi:10.2307/2336663.
-
Burnham KP, Anderson DR (1998). “Practical use of the information-theoretic approach.” In Model selection and inference, 75–117. Springer. doi:10.1007/978-1-4757-2917-7_3.
-
GaĆecki A, Burzykowski T (2013). “Linear mixed-effects model.” In Linear mixed-effects models using R, 245–273. Springer.
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 |
( |
sym |
( |
... |
Additional arguments passed to |
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 |
( |
... |
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.
Refitting MMRM with Multiple Optimizers
Description
Usage
refit_multiple_optimizers(fit, ..., control = mmrm_control(...))
Arguments
fit |
( |
... |
Additional arguments passed to |
control |
( |
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 |
( |
ver |
( |
callback |
( |
message |
( |
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 |
( |
n_visits |
( |
n_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 |
( |
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 |
( |
Value
x
if successful, or an error is thrown otherwise.