Movatterモバイル変換


[0]ホーム

URL:


Title:Bayesian MMRMs using 'brms'
Version:1.1.1
Description:The mixed model for repeated measures (MMRM) is a popular model for longitudinal clinical trial data with continuous endpoints, and 'brms' is a powerful and versatile package for fitting Bayesian regression models. The 'brms.mmrm' R package leverages 'brms' to run MMRMs, and it supports a simplified interfaced to reduce difficulty and align with the best practices of the life sciences. References: Bürkner (2017) <doi:10.18637/jss.v080.i01>, Mallinckrodt (2008) <doi:10.1177/009286150804200402>.
License:MIT + file LICENSE
URL:https://openpharma.github.io/brms.mmrm/,https://github.com/openpharma/brms.mmrm
BugReports:https://github.com/openpharma/brms.mmrm/issues
Depends:R (≥ 4.0.0)
Imports:brms (≥ 2.19.0), dplyr, ggplot2, ggridges, MASS, posterior,purrr, rlang, stats, tibble, tidyr, tidyselect, trialr, utils,zoo
Suggests:BH, emmeans (≥ 1.8.7), fst, gt, gtsummary, knitr (≥ 1.30),markdown (≥ 1.1), mmrm, parallel, Rcpp, RcppEigen,RcppParallel, rmarkdown (≥ 2.4), rstan, StanHeaders, testthat(≥ 3.0.0)
VignetteBuilder:knitr
Config/testthat/edition:3
Encoding:UTF-8
Language:en-US
RoxygenNote:7.3.2
NeedsCompilation:no
Packaged:2024-10-02 19:39:46 UTC; C240390
Author:William Michael LandauORCID iD [aut, cre], Kevin KunzmannORCID iD [aut], Yoni Sidi [aut], Christian StockORCID iD [aut], Eli Lilly and Company [cph, fnd], Boehringer Ingelheim Pharma GmbH & Co. KG [cph, fnd]
Maintainer:William Michael Landau <will.landau.oss@gmail.com>
Repository:CRAN
Date/Publication:2024-10-02 20:10:01 UTC

brms.mmrm: Bayesian MMRMs usingbrms

Description

The mixed model for repeated measures (MMRM) is apopular model for longitudinal clinical trial data withcontinuous endpoints, andbrms a is powerful and versatilepackage for fitting Bayesian regression models.Thebrms.mmrm R package leveragesbrms to run MMRMs, andit supports a simplified interfaced to reduce difficultyand align with the best practices of the life sciences.

References


Cell-means-like time-averaged archetype

Description

Create a cell-means-like informative prior archetypewith a special fixed effect to represent the average across time.

Usage

brm_archetype_average_cells(  data,  intercept = FALSE,  baseline = !is.null(attr(data, "brm_baseline")),  baseline_subgroup = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_subgroup_time = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_time = !is.null(attr(data, "brm_baseline")),  covariates = TRUE,  prefix_interest = "x_",  prefix_nuisance = "nuisance_")

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

intercept

Logical of length 1.TRUE (default) to include an intercept,FALSE to omit.

baseline

Logical of length 1.TRUE to include an additive effect for baselineresponse,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_subgroup

Logical of length 1.

baseline_subgroup_time

Logical of length 1.TRUE to include baseline-by-subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared baselineand subgroup variables in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_time

Logical of length 1.TRUE to include baseline-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

covariates

Logical of length 1.TRUE (default) to include any additive covariates declared withthecovariates argument ofbrm_data(),FALSE to omit.For informative prior archetypes, this option is set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

prefix_interest

Character string to prepend to the new columnsof generated fixed effects of interest (relating to group, subgroup,and/or time).In rare cases, you may need to set a non-default prefix to preventname conflicts with existing columns in the data, or renamethe columns in your data.prefix_interest must not be the same value asprefix_nuisance.

prefix_nuisance

Same asprefix_interest, but relating togenerated fixed effects NOT of interest (not relating to group,subgroup, or time). Must not be the same value asprefix_interest.

Details

This archetype has a special fixed effect for each treatment groupto represent the mean response averaged across all the time points.

To illustrate, suppose the dataset has two treatment groups A and B,time points 1, 2, and 3, and no other covariates.

Letmu_gt be the marginal mean of the response at groupg timet given data and hyperparameters.The model has fixed effect parametersbeta_1,beta_2, ...,beta_6which express the marginal meansmu_gt as follows:

  `mu_A1 = 3 * beta_1 - beta_2 - beta_3`  `mu_A2 = beta_2`  `mu_A3 = beta_3`  `mu_B1 = 3 * beta_4 - beta_5 - beta_6`  `mu_B2 = beta_5`  `mu_B3 = beta_6`

For group A,beta_1 is the average response in group Aaveraged across time points. You can confirm this yourselfby expressing the average across time(mu_A1 + mu_A2 + mu_A3) / 3 in terms of the⁠beta_*⁠ parametersand confirming that the expression simplifies down to justbeta_1.beta_2 represents the mean response in group A at time 2, andbeta_3 represents the mean response in group A at time 3.beta_4,beta_5, andbeta_6 are analogous for group B.

Value

A special classedtibble with data tailored tothe cell-means-like time-averaged archetype. The dataset is augmentedwith extra columns with the"archetype_" prefix, as well as specialattributes to tell downstream functions likebrm_formula() what todo with the object.

Prior labeling forbrm_archetype_average_cells()

Within each treatment group, the initial time point representsthe average, and each successive time point represents the responsewithin that actual time.To illustrate, consider the example in the Details section.In the labeling scheme forbrm_archetype_average_cells(),you can label the prior onbeta_1 usingbrm_prior_label(code = "normal(1.2, 5)", group = "A", time = "1").Similarly, you cal label the prior onbeta_5 withbrm_prior_label(code = "normal(1.3, 7)", group = "B", time = "2").To confirm that you set the prior correctly, compare thebrms priorwith the output ofsummary(your_archetype).See the examples for details.

Nuisance variables

In the presence of covariate adjustment, functions likebrm_archetype_successive_cells() convert nuisance factors into binarydummy variables, then center all those dummy variables and anycontinuous nuisance variables at their means in the data.This ensures that the main model coefficientsof interest are not implicitly conditional on a subset of the data.In other words, preprocessing nuisance variables this way preservesthe interpretations of the fixed effects of interest, and it ensuresinformative priors can be specified correctly.

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other informative prior archetypes:brm_archetype_average_effects(),brm_archetype_cells(),brm_archetype_effects(),brm_archetype_successive_cells(),brm_archetype_successive_effects()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )dplyr::select(  data,  group,  time,  patient,  starts_with("biomarker"),  starts_with("status"))archetype <- brm_archetype_average_cells(data)archetypesummary(archetype)formula <- brm_formula(archetype)formulaprior <- brm_prior_label(  code = "normal(1, 2.2)",  group = "group_1",  time = "time_2") |>  brm_prior_label("normal(1, 3.3)", group = "group_1", time = "time_3") |>  brm_prior_label("normal(1, 4.4)", group = "group_1", time = "time_4") |>  brm_prior_label("normal(2, 2.2)", group = "group_2", time = "time_2") |>  brm_prior_label("normal(2, 3.3)", group = "group_2", time = "time_3") |>  brm_prior_label("normal(2, 4.4)", group = "group_2", time = "time_4") |>  brm_prior_archetype(archetype)priorclass(prior)if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = archetype,        formula = formula,        prior = prior,        chains = 1,        iter = 100,        refresh = 0      )    )  ))suppressWarnings(print(model))brms::prior_summary(model)draws <- brm_marginal_draws(  data = archetype,  formula = formula,  model = model)summaries_model <- brm_marginal_summaries(draws)summaries_data <- brm_marginal_data(data)brm_plot_compare(model = summaries_model, data = summaries_data)}

Treatment effect time-averaged archetype

Description

Create a treatment effect informative prior archetypewith a special fixed effect to represent the average across time.

Usage

brm_archetype_average_effects(  data,  intercept = FALSE,  baseline = !is.null(attr(data, "brm_baseline")),  baseline_subgroup = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_subgroup_time = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_time = !is.null(attr(data, "brm_baseline")),  covariates = TRUE,  prefix_interest = "x_",  prefix_nuisance = "nuisance_")

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

intercept

Logical of length 1.TRUE (default) to include an intercept,FALSE to omit.

baseline

Logical of length 1.TRUE to include an additive effect for baselineresponse,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_subgroup

Logical of length 1.

baseline_subgroup_time

Logical of length 1.TRUE to include baseline-by-subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared baselineand subgroup variables in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_time

Logical of length 1.TRUE to include baseline-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

covariates

Logical of length 1.TRUE (default) to include any additive covariates declared withthecovariates argument ofbrm_data(),FALSE to omit.For informative prior archetypes, this option is set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

prefix_interest

Character string to prepend to the new columnsof generated fixed effects of interest (relating to group, subgroup,and/or time).In rare cases, you may need to set a non-default prefix to preventname conflicts with existing columns in the data, or renamethe columns in your data.prefix_interest must not be the same value asprefix_nuisance.

prefix_nuisance

Same asprefix_interest, but relating togenerated fixed effects NOT of interest (not relating to group,subgroup, or time). Must not be the same value asprefix_interest.

Details

This archetype has a special fixed effect for each treatment groupto represent the mean response averaged across all the time points,and treatment effects are explicitly parameterized.

To illustrate, suppose the dataset has two treatment groups A(placebo/reference group) and B (active/non-reference group),time points 1, 2, and 3, and no other covariates.Letmu_gt be the marginal mean of the response at groupg timet given data and hyperparameters.The model has fixed effect parametersbeta_1,beta_2, ...,beta_6which express the marginal meansmu_gt as follows:

`mu_A1 = 3 * beta_1 - beta_2 - beta_3``mu_A2 = beta_2``mu_A3 = beta_3``mu_B1 = 3 * beta_1 - beta_2 - beta_3 + 3 * beta_4 - beta_5 - beta_6``mu_B2 = beta_2 + beta_5``mu_B3 = beta_3 + beta_6`

For group A,beta_1 is the average response in group Aaveraged across time points. You can confirm this yourselfby expressing the average across time(mu_A1 + mu_A2 + mu_A3) / 3 in terms of the⁠beta_*⁠ parametersand confirming that the expression simplifies down to justbeta_1.beta_2 represents the mean response in group A at time 2, andbeta_3 represents the mean response in group A at time 3.beta_4 is the treatment effect of group B relative to group A,averaged across time points.beta_5 is the treatment effect of B vs Aat time 2, andbeta_6 is analogous for time 3.

Value

A special classedtibble with data tailored tothe treatment effect time-averaged archetype. The dataset is augmentedwith extra columns with the"archetype_" prefix, as well as specialattributes to tell downstream functions likebrm_formula() what todo with the object.

Prior labeling forbrm_archetype_average_effects()

Within each treatment group, the initial time point representsthe average, and each successive time point represents the responsewithin that actual time.To illustrate, consider the example in the Details section.In the labeling scheme forbrm_archetype_average_effects(),you can label the prior onbeta_1 usingbrm_prior_label(code = "normal(1.2, 5)", group = "A", time = "1").Similarly, you cal label the prior onbeta_5 withbrm_prior_label(code = "normal(1.3, 7)", group = "B", time = "2").To confirm that you set the prior correctly, compare thebrms priorwith the output ofsummary(your_archetype).See the examples for details.

Nuisance variables

In the presence of covariate adjustment, functions likebrm_archetype_successive_cells() convert nuisance factors into binarydummy variables, then center all those dummy variables and anycontinuous nuisance variables at their means in the data.This ensures that the main model coefficientsof interest are not implicitly conditional on a subset of the data.In other words, preprocessing nuisance variables this way preservesthe interpretations of the fixed effects of interest, and it ensuresinformative priors can be specified correctly.

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other informative prior archetypes:brm_archetype_average_cells(),brm_archetype_cells(),brm_archetype_effects(),brm_archetype_successive_cells(),brm_archetype_successive_effects()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )dplyr::select(  data,  group,  time,  patient,  starts_with("biomarker"),  starts_with("status"))archetype <- brm_archetype_average_effects(data)archetypesummary(archetype)formula <- brm_formula(archetype)formulaprior <- brm_prior_label(  code = "normal(1, 2.2)",  group = "group_1",  time = "time_2") |>  brm_prior_label("normal(1, 3.3)", group = "group_1", time = "time_3") |>  brm_prior_label("normal(1, 4.4)", group = "group_1", time = "time_4") |>  brm_prior_label("normal(2, 2.2)", group = "group_2", time = "time_2") |>  brm_prior_label("normal(2, 3.3)", group = "group_2", time = "time_3") |>  brm_prior_label("normal(2, 4.4)", group = "group_2", time = "time_4") |>  brm_prior_archetype(archetype)priorclass(prior)if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = archetype,        formula = formula,        prior = prior,        chains = 1,        iter = 100,        refresh = 0      )    )  ))suppressWarnings(print(model))brms::prior_summary(model)draws <- brm_marginal_draws(  data = archetype,  formula = formula,  model = model)summaries_model <- brm_marginal_summaries(draws)summaries_data <- brm_marginal_data(data)brm_plot_compare(model = summaries_model, data = summaries_data)}

Cell means archetype

Description

Create an informative prior archetype for cell means.

Usage

brm_archetype_cells(  data,  intercept = FALSE,  baseline = !is.null(attr(data, "brm_baseline")),  baseline_subgroup = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_subgroup_time = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_time = !is.null(attr(data, "brm_baseline")),  covariates = TRUE,  clda = FALSE,  prefix_interest = "x_",  prefix_nuisance = "nuisance_")

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

intercept

TRUE to make one of the parameters an intercept,FALSE otherwise. IfTRUE, then the interpretation of theparameters in the "Details" section will change, and you areresponsible for manually callingsummary() on the archetypeand interpreting the parameters according to the output.In addition, you are responsible for setting anappropriate prior on the intercept. In normal usage,brms looks fora model parameter called"Intercept" and uses the data to set the priorto help the MCMC runs smoothly. Ifintercept = TRUE for informativeprior archetypes, the intercept will be called something else, andbrms cannot auto-generate a sensible default prior.

baseline

Logical of length 1.TRUE to include an additive effect for baselineresponse,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_subgroup

Logical of length 1.

baseline_subgroup_time

Logical of length 1.TRUE to include baseline-by-subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared baselineand subgroup variables in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_time

Logical of length 1.TRUE to include baseline-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

covariates

Logical of length 1.TRUE (default) to include any additive covariates declared withthecovariates argument ofbrm_data(),FALSE to omit.For informative prior archetypes, this option is set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

clda

TRUE to opt into constrained longitudinal data analysis(cLDA),FALSE otherwise. To use cLDA,reference_time must have beennon-NULL in the call tobrm_data() used to construct the data.

Some archetypes cannot support cLDA(e.g.brm_archetype_average_cells() andbrm_archetype_average_effects()).

In cLDA, the fixed effects parameterizationis restricted such that all treatment groups are pooled at baseline.(If you supplied asubgroup variable inbrm_data(), thenthis constraint is applied separately within each subgroup variable.)cLDA may result in more precise estimates when thetime variablehas a baseline level and the baseline outcomes are recordedbefore randomization in a clinical trial.

prefix_interest

Character string to prepend to the new columnsof generated fixed effects of interest (relating to group, subgroup,and/or time).In rare cases, you may need to set a non-default prefix to preventname conflicts with existing columns in the data, or renamethe columns in your data.prefix_interest must not be the same value asprefix_nuisance.

prefix_nuisance

Same asprefix_interest, but relating togenerated fixed effects NOT of interest (not relating to group,subgroup, or time). Must not be the same value asprefix_interest.

Details

In this archetype, each fixed effect is a cell mean: the groupmean for a given value of treatment group and discrete time(and subgroup level, if applicable).

Value

A special classedtibble with data tailored tothe successive differences archetype. The dataset is augmented withextra columns with the"archetype_" prefix, as well as specialattributes to tell downstream functions likebrm_formula() what todo with the object.

Prior labeling forbrm_archetype_cells()

Within each treatment group, each model parameter is a cell mean,and the labeling scheme inbrm_prior_label() andbrm_prior_archetype() translate easily. For example,brm_prior_label(code = "normal(1.2, 5)", group = "B", time = "VISIT2")declares anormal(1.2, 5) prior on the cell mean of treatmentgroupB at discrete time pointVISIT2.To confirm that you set the prior correctly, compare thebrms priorwith the output ofsummary(your_archetype).See the examples for details.

Nuisance variables

In the presence of covariate adjustment, functions likebrm_archetype_successive_cells() convert nuisance factors into binarydummy variables, then center all those dummy variables and anycontinuous nuisance variables at their means in the data.This ensures that the main model coefficientsof interest are not implicitly conditional on a subset of the data.In other words, preprocessing nuisance variables this way preservesthe interpretations of the fixed effects of interest, and it ensuresinformative priors can be specified correctly.

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other informative prior archetypes:brm_archetype_average_cells(),brm_archetype_average_effects(),brm_archetype_effects(),brm_archetype_successive_cells(),brm_archetype_successive_effects()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )dplyr::select(  data,  group,  time,  patient,  starts_with("biomarker"),  starts_with("status"))archetype <- brm_archetype_cells(data)archetypesummary(archetype)formula <- brm_formula(archetype)formulaprior <- brm_prior_label(  code = "normal(1, 2.2)",  group = "group_1",  time = "time_2") |>  brm_prior_label("normal(1, 3.3)", group = "group_1", time = "time_3") |>  brm_prior_label("normal(1, 4.4)", group = "group_1", time = "time_4") |>  brm_prior_label("normal(2, 2.2)", group = "group_2", time = "time_2") |>  brm_prior_label("normal(2, 3.3)", group = "group_2", time = "time_3") |>  brm_prior_label("normal(2, 4.4)", group = "group_2", time = "time_4") |>  brm_prior_archetype(archetype)priorclass(prior)if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = archetype,        formula = formula,        prior = prior,        chains = 1,        iter = 100,        refresh = 0      )    )  ))suppressWarnings(print(model))brms::prior_summary(model)draws <- brm_marginal_draws(  data = archetype,  formula = formula,  model = model)summaries_model <- brm_marginal_summaries(draws)summaries_data <- brm_marginal_data(data)brm_plot_compare(model = summaries_model, data = summaries_data)}

Treatment effect archetype

Description

Create an informative prior archetype for a simple treatmenteffect parameterization.

Usage

brm_archetype_effects(  data,  intercept = FALSE,  baseline = !is.null(attr(data, "brm_baseline")),  baseline_subgroup = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_subgroup_time = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_time = !is.null(attr(data, "brm_baseline")),  covariates = TRUE,  clda = FALSE,  prefix_interest = "x_",  prefix_nuisance = "nuisance_")

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

intercept

TRUE to make one of the parameters an intercept,FALSE otherwise. IfTRUE, then the interpretation of theparameters in the "Details" section will change, and you areresponsible for manually callingsummary() on the archetypeand interpreting the parameters according to the output.In addition, you are responsible for setting anappropriate prior on the intercept. In normal usage,brms looks fora model parameter called"Intercept" and uses the data to set the priorto help the MCMC runs smoothly. Ifintercept = TRUE for informativeprior archetypes, the intercept will be called something else, andbrms cannot auto-generate a sensible default prior.

baseline

Logical of length 1.TRUE to include an additive effect for baselineresponse,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_subgroup

Logical of length 1.

baseline_subgroup_time

Logical of length 1.TRUE to include baseline-by-subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared baselineand subgroup variables in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_time

Logical of length 1.TRUE to include baseline-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

covariates

Logical of length 1.TRUE (default) to include any additive covariates declared withthecovariates argument ofbrm_data(),FALSE to omit.For informative prior archetypes, this option is set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

clda

TRUE to opt into constrained longitudinal data analysis(cLDA),FALSE otherwise. To use cLDA,reference_time must have beennon-NULL in the call tobrm_data() used to construct the data.

Some archetypes cannot support cLDA(e.g.brm_archetype_average_cells() andbrm_archetype_average_effects()).

In cLDA, the fixed effects parameterizationis restricted such that all treatment groups are pooled at baseline.(If you supplied asubgroup variable inbrm_data(), thenthis constraint is applied separately within each subgroup variable.)cLDA may result in more precise estimates when thetime variablehas a baseline level and the baseline outcomes are recordedbefore randomization in a clinical trial.

prefix_interest

Character string to prepend to the new columnsof generated fixed effects of interest (relating to group, subgroup,and/or time).In rare cases, you may need to set a non-default prefix to preventname conflicts with existing columns in the data, or renamethe columns in your data.prefix_interest must not be the same value asprefix_nuisance.

prefix_nuisance

Same asprefix_interest, but relating togenerated fixed effects NOT of interest (not relating to group,subgroup, or time). Must not be the same value asprefix_interest.

Details

In this archetype, each fixed effect is either a placebo responseor a treatment effect.

To illustrate, suppose the dataset has two treatment groups A and B,time points 1, 2, and 3, and no other covariates. Assume group Ais the reference group (e.g. placebo).Letmu_gt be the marginal mean of the response at groupg timet given data and hyperparameters.The model has fixed effect parametersbeta_1,beta_2, ...,beta_6which express the marginal meansmu_gt as follows:

  `mu_A1 = beta_1`  `mu_A2 = beta_2`  `mu_A3 = beta_3`  `mu_B1 = beta_1 + beta_4`  `mu_B2 = beta_2 + beta_5`  `mu_B3 = beta_3 + beta_6`

Above,beta_2 is the group mean of treatment group A at time 2,andbeta_5 is the treatment effect of B relative to A at time 2.

Value

A special classedtibble with data tailored tothe successive differences archetype. The dataset is augmented withextra columns with the"archetype_" prefix, as well as specialattributes to tell downstream functions likebrm_formula() what todo with the object.

Prior labeling forbrm_archetype_effects()

In the reference group (e.g. placebo) each fixed effect is a cellmean at a time point. In each non-reference group, each fixed effectis the treatment effect relative to the reference (at a time point).The labeling scheme inbrm_prior_label() andbrm_prior_archetype() translate straightforwardly. For example,brm_prior_label(code = "normal(1.2, 5)", group = "A", time = "2")declares anormal(1.2, 5) onbeta_2 (cell mean of the referencegroup at time 2). Similarly,brm_prior_label(code = "normal(1.3, 6)", group = "B", time = "2")declares anormal(1.3, 6) prior on the treatment effect of groupB relative to groupA at discrete time point2.To confirm that you set the prior correctly, compare thebrms priorwith the output ofsummary(your_archetype).See the examples for details.

Nuisance variables

In the presence of covariate adjustment, functions likebrm_archetype_successive_cells() convert nuisance factors into binarydummy variables, then center all those dummy variables and anycontinuous nuisance variables at their means in the data.This ensures that the main model coefficientsof interest are not implicitly conditional on a subset of the data.In other words, preprocessing nuisance variables this way preservesthe interpretations of the fixed effects of interest, and it ensuresinformative priors can be specified correctly.

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other informative prior archetypes:brm_archetype_average_cells(),brm_archetype_average_effects(),brm_archetype_cells(),brm_archetype_successive_cells(),brm_archetype_successive_effects()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )dplyr::select(  data,  group,  time,  patient,  starts_with("biomarker"),  starts_with("status"))archetype <- brm_archetype_effects(data)archetypesummary(archetype)formula <- brm_formula(archetype)formulaprior <- brm_prior_label(  code = "normal(1, 2.2)",  group = "group_1",  time = "time_2") |>  brm_prior_label("normal(1, 3.3)", group = "group_1", time = "time_3") |>  brm_prior_label("normal(1, 4.4)", group = "group_1", time = "time_4") |>  brm_prior_label("normal(2, 2.2)", group = "group_2", time = "time_2") |>  brm_prior_label("normal(2, 3.3)", group = "group_2", time = "time_3") |>  brm_prior_label("normal(2, 4.4)", group = "group_2", time = "time_4") |>  brm_prior_archetype(archetype)priorclass(prior)if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = archetype,        formula = formula,        prior = prior,        chains = 1,        iter = 100,        refresh = 0      )    )  ))suppressWarnings(print(model))brms::prior_summary(model)draws <- brm_marginal_draws(  data = archetype,  formula = formula,  model = model)summaries_model <- brm_marginal_summaries(draws)summaries_data <- brm_marginal_data(data)brm_plot_compare(model = summaries_model, data = summaries_data)}

Cell-means-like successive differences archetype

Description

Create an informative prior archetype where the fixed effectsare successive differences between adjacent time points.

Usage

brm_archetype_successive_cells(  data,  intercept = FALSE,  baseline = !is.null(attr(data, "brm_baseline")),  baseline_subgroup = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_subgroup_time = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_time = !is.null(attr(data, "brm_baseline")),  covariates = TRUE,  clda = FALSE,  prefix_interest = "x_",  prefix_nuisance = "nuisance_")

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

intercept

TRUE to make one of the parameters an intercept,FALSE otherwise. IfTRUE, then the interpretation of theparameters in the "Details" section will change, and you areresponsible for manually callingsummary() on the archetypeand interpreting the parameters according to the output.In addition, you are responsible for setting anappropriate prior on the intercept. In normal usage,brms looks fora model parameter called"Intercept" and uses the data to set the priorto help the MCMC runs smoothly. Ifintercept = TRUE for informativeprior archetypes, the intercept will be called something else, andbrms cannot auto-generate a sensible default prior.

baseline

Logical of length 1.TRUE to include an additive effect for baselineresponse,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_subgroup

Logical of length 1.

baseline_subgroup_time

Logical of length 1.TRUE to include baseline-by-subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared baselineand subgroup variables in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_time

Logical of length 1.TRUE to include baseline-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

covariates

Logical of length 1.TRUE (default) to include any additive covariates declared withthecovariates argument ofbrm_data(),FALSE to omit.For informative prior archetypes, this option is set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

clda

TRUE to opt into constrained longitudinal data analysis(cLDA),FALSE otherwise. To use cLDA,reference_time must have beennon-NULL in the call tobrm_data() used to construct the data.

Some archetypes cannot support cLDA(e.g.brm_archetype_average_cells() andbrm_archetype_average_effects()).

In cLDA, the fixed effects parameterizationis restricted such that all treatment groups are pooled at baseline.(If you supplied asubgroup variable inbrm_data(), thenthis constraint is applied separately within each subgroup variable.)cLDA may result in more precise estimates when thetime variablehas a baseline level and the baseline outcomes are recordedbefore randomization in a clinical trial.

prefix_interest

Character string to prepend to the new columnsof generated fixed effects of interest (relating to group, subgroup,and/or time).In rare cases, you may need to set a non-default prefix to preventname conflicts with existing columns in the data, or renamethe columns in your data.prefix_interest must not be the same value asprefix_nuisance.

prefix_nuisance

Same asprefix_interest, but relating togenerated fixed effects NOT of interest (not relating to group,subgroup, or time). Must not be the same value asprefix_interest.

Details

In this archetype, each fixed effect is either an intercepton the first time point or the difference between two adjacent timepoints, and each treatment group has its own set of fixed effectsindependent of the other treatment groups.

To illustrate, suppose the dataset has two treatment groups A and B,time points 1, 2, and 3, and no other covariates.Letmu_gt be the marginal mean of the response at groupg timet given data and hyperparameters.The model has fixed effect parametersbeta_1,beta_2, ...,beta_6which express the marginal meansmu_gt as follows:

  `mu_A1 = beta_1`  `mu_A2 = beta_1 + beta_2`  `mu_A3 = beta_1 + beta_2 + beta_3`  `mu_B1 = beta_4`  `mu_B2 = beta_4 + beta_5`  `mu_B3 = beta_4 + beta_5 + beta_6`

For group A,beta_1 is the time 1 intercept,beta_2 representstime 2 minus time 1, andbeta_3 represents time 3 minus time 2.beta_4,beta_5, andbeta_6 behave analogously for group B.

Value

A special classedtibble with data tailored tothe successive differences archetype. The dataset is augmented withextra columns with the"archetype_" prefix, as well as specialattributes to tell downstream functions likebrm_formula() what todo with the object.

Nuisance variables

In the presence of covariate adjustment, functions likebrm_archetype_successive_cells() convert nuisance factors into binarydummy variables, then center all those dummy variables and anycontinuous nuisance variables at their means in the data.This ensures that the main model coefficientsof interest are not implicitly conditional on a subset of the data.In other words, preprocessing nuisance variables this way preservesthe interpretations of the fixed effects of interest, and it ensuresinformative priors can be specified correctly.

Prior labeling forbrm_archetype_successive_cells()

Within each treatment group, each intercept is labeled by the earliesttime point, and each successive difference term gets the successivetime point as the label.To illustrate, consider the example in the Details section.In the labeling scheme forbrm_archetype_successive_cells(),you can label the prior onbeta_1 usingbrm_prior_label(code = "normal(1.2, 5)", group = "A", time = "1").Similarly, you cal label the prior onbeta_5 withbrm_prior_label(code = "normal(1.3, 7)", group = "B", time = "2").To confirm that you set the prior correctly, compare thebrms priorwith the output ofsummary(your_archetype).See the examples for details.

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other informative prior archetypes:brm_archetype_average_cells(),brm_archetype_average_effects(),brm_archetype_cells(),brm_archetype_effects(),brm_archetype_successive_effects()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )dplyr::select(  data,  group,  time,  patient,  starts_with("biomarker"),  starts_with("status"))archetype <- brm_archetype_successive_cells(data)archetypesummary(archetype)formula <- brm_formula(archetype)formulaprior <- brm_prior_label(  code = "normal(1, 2.2)",  group = "group_1",  time = "time_2") |>  brm_prior_label("normal(1, 3.3)", group = "group_1", time = "time_3") |>  brm_prior_label("normal(1, 4.4)", group = "group_1", time = "time_4") |>  brm_prior_label("normal(2, 2.2)", group = "group_2", time = "time_2") |>  brm_prior_label("normal(2, 3.3)", group = "group_2", time = "time_3") |>  brm_prior_label("normal(2, 4.4)", group = "group_2", time = "time_4") |>  brm_prior_archetype(archetype)priorclass(prior)if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = archetype,        formula = formula,        prior = prior,        chains = 1,        iter = 100,        refresh = 0      )    )  ))suppressWarnings(print(model))brms::prior_summary(model)draws <- brm_marginal_draws(  data = archetype,  formula = formula,  model = model)summaries_model <- brm_marginal_summaries(draws)summaries_data <- brm_marginal_data(data)brm_plot_compare(model = summaries_model, data = summaries_data)}

Treatment-effect-like successive differences archetype

Description

Create an informative prior archetype where the fixed effectsare successive differences between adjacent time points and termsin non-reference groups are treatment effects.

Usage

brm_archetype_successive_effects(  data,  intercept = FALSE,  baseline = !is.null(attr(data, "brm_baseline")),  baseline_subgroup = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_subgroup_time = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_time = !is.null(attr(data, "brm_baseline")),  covariates = TRUE,  clda = FALSE,  prefix_interest = "x_",  prefix_nuisance = "nuisance_")

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

intercept

Logical of length 1.TRUE (default) to include an intercept,FALSE to omit.

baseline

Logical of length 1.TRUE to include an additive effect for baselineresponse,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_subgroup

Logical of length 1.

baseline_subgroup_time

Logical of length 1.TRUE to include baseline-by-subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared baselineand subgroup variables in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_time

Logical of length 1.TRUE to include baseline-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

covariates

Logical of length 1.TRUE (default) to include any additive covariates declared withthecovariates argument ofbrm_data(),FALSE to omit.For informative prior archetypes, this option is set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

clda

TRUE to opt into constrained longitudinal data analysis(cLDA),FALSE otherwise. To use cLDA,reference_time must have beennon-NULL in the call tobrm_data() used to construct the data.

Some archetypes cannot support cLDA(e.g.brm_archetype_average_cells() andbrm_archetype_average_effects()).

In cLDA, the fixed effects parameterizationis restricted such that all treatment groups are pooled at baseline.(If you supplied asubgroup variable inbrm_data(), thenthis constraint is applied separately within each subgroup variable.)cLDA may result in more precise estimates when thetime variablehas a baseline level and the baseline outcomes are recordedbefore randomization in a clinical trial.

prefix_interest

Character string to prepend to the new columnsof generated fixed effects of interest (relating to group, subgroup,and/or time).In rare cases, you may need to set a non-default prefix to preventname conflicts with existing columns in the data, or renamethe columns in your data.prefix_interest must not be the same value asprefix_nuisance.

prefix_nuisance

Same asprefix_interest, but relating togenerated fixed effects NOT of interest (not relating to group,subgroup, or time). Must not be the same value asprefix_interest.

Details

Within the reference treatment group (e.g. placebo),each fixed effect is either an intercepton the first time point or the difference between two adjacent timepoints. In each non-reference treatment group,each model parameter is defined as an effect relative to thereference group.

To illustrate, suppose the dataset has two treatment groups A and B,time points 1, 2, and 3, and no other covariates.Say group A is the reference group (e.g. placebo).Letmu_gt be the marginal mean of the response at groupg timet given data and hyperparameters.The model has fixed effect parametersbeta_1,beta_2, ...,beta_6which express the marginal meansmu_gt as follows:

  `mu_A1 = beta_1`  `mu_A2 = beta_1 + beta_2`  `mu_A3 = beta_1 + beta_2 + beta_3`  `mu_B1 = beta_1 + beta_4`  `mu_B2 = beta_1 + beta_2 + beta_4 + beta_5`  `mu_B3 = beta_1 + beta_2 + beta_3 + beta_4 + beta_5 + beta_6`

For group A,beta_1 is the time 1 intercept,beta_2 representstime 2 minus time 1, andbeta_3 represents time 3 minus time 2.beta_4 is the treatment effect of group B relative to group A attime 1.beta_5 is the treatment effect of the difference betweentimes 2 and 1, relative to treatment group A.Similarly,beta_6 is the treatment effect of the difference betweentimes 3 and 2, relative to treatment group A.

Value

A special classedtibble with data tailored tothe successive differences archetype. The dataset is augmented withextra columns with the"archetype_" prefix, as well as specialattributes to tell downstream functions likebrm_formula() what todo with the object.

Prior labeling forbrm_archetype_successive_effects()

Within each treatment group, each intercept is labeled by the earliesttime point, and each successive difference term gets the successivetime point as the label.To illustrate, consider the example in the Details section.In the labeling scheme forbrm_archetype_successive_effects(),you can label the prior onbeta_1 usingbrm_prior_label(code = "normal(1.2, 5)", group = "A", time = "1").Similarly, you cal label the prior onbeta_5 withbrm_prior_label(code = "normal(1.3, 7)", group = "B", time = "2").To confirm that you set the prior correctly, compare thebrms priorwith the output ofsummary(your_archetype).See the examples for details.

Nuisance variables

In the presence of covariate adjustment, functions likebrm_archetype_successive_cells() convert nuisance factors into binarydummy variables, then center all those dummy variables and anycontinuous nuisance variables at their means in the data.This ensures that the main model coefficientsof interest are not implicitly conditional on a subset of the data.In other words, preprocessing nuisance variables this way preservesthe interpretations of the fixed effects of interest, and it ensuresinformative priors can be specified correctly.

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other informative prior archetypes:brm_archetype_average_cells(),brm_archetype_average_effects(),brm_archetype_cells(),brm_archetype_effects(),brm_archetype_successive_cells()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )dplyr::select(  data,  group,  time,  patient,  starts_with("biomarker"),  starts_with("status"))archetype <- brm_archetype_successive_effects(data)archetypesummary(archetype)formula <- brm_formula(archetype)formulaprior <- brm_prior_label(  code = "normal(1, 2.2)",  group = "group_1",  time = "time_2") |>  brm_prior_label("normal(1, 3.3)", group = "group_1", time = "time_3") |>  brm_prior_label("normal(1, 4.4)", group = "group_1", time = "time_4") |>  brm_prior_label("normal(2, 2.2)", group = "group_2", time = "time_2") |>  brm_prior_label("normal(2, 3.3)", group = "group_2", time = "time_3") |>  brm_prior_label("normal(2, 4.4)", group = "group_2", time = "time_4") |>  brm_prior_archetype(archetype)priorclass(prior)if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = archetype,        formula = formula,        prior = prior,        chains = 1,        iter = 100,        refresh = 0      )    )  ))suppressWarnings(print(model))brms::prior_summary(model)draws <- brm_marginal_draws(  data = archetype,  formula = formula,  model = model)summaries_model <- brm_marginal_summaries(draws)summaries_data <- brm_marginal_data(data)brm_plot_compare(model = summaries_model, data = summaries_data)}

Create and preprocess an MMRM dataset.

Description

Create a dataset to analyze with an MMRM.

Usage

brm_data(  data,  outcome,  baseline = NULL,  group,  subgroup = NULL,  time,  patient,  covariates = character(0L),  missing = NULL,  reference_group,  reference_subgroup = NULL,  reference_time = NULL,  role = NULL,  level_baseline = NULL,  level_control = NULL)

Arguments

data

Data frame or tibble with longitudinal data.

outcome

Character of length 1, name of the continuousoutcome variable.Example possibilities from clinical trial datasets include"CHG" and"AVAL".Theoutcome column in the data should be a numeric vector.

baseline

Character of length 1,name of the baseline response variable (for example,"BASE"in many clinical trial datasets).Only relevant if the response variable is change from baseline.SupplyNULL to ignore or omit.

group

Character of length 1, name of the treatment group variable.Example possibilities from clinical trial datasets include"TRT01P","TREATMENT","TRT", and"GROUP".Thegroup column in the data should be acharacter vector or unordered factor.

subgroup

Character of length 1, optional name of the adiscrete subgroup variable. Set toNULL to omit the subgroup (default).If present, thesubgroup column in the data should be acharacter vector or unordered factor.

time

Character of length 1, name of the discrete time variable.Example possibilities from clinical trial datasets include"AVISIT" and"VISIT".For most analyses, please ensure the time column in the datais an ordered factor. You can easily turnthe time variable into an ordered factor usingbrm_data_chronologize(), either before or immediately afterbrm_data() (but before any⁠brm_archetype_*()⁠ functions).This ensures the time points sort in chronological order,which ensures the correctness of informative prior archetypes andautoregressive / moving average correlation structures.

Ordinarily, ordered factors automatically use polynomial contrasts fromcontr.poly(). This is undesirable for MMRMs, so if the time variableis an ordered factor, thenbrm_data()manually setscontrasts(data[[time]]) to a set of treatment contrastsusingcontr.treatment(). If you prefer different contrasts, pleasemanually setcontrasts(data[[time]]) to something else aftercallingbrm_data().

patient

Character of length 1, name of the patient ID variable.Example possibilities from clinical trial datasets include"USUBJID","SUBJID","PATIENT","PATIENTID","SUBJECT","SUBJIDID","SBJID","STYSID1A","SBJ1N", and"ID".Thepatient column in the data should be a factor or character vector.

covariates

Character vector of names of other covariates.All these covariates are assumed to be non-time-varying. For time-varyingcovariates, please manually expand the data to the full grid of patientsand time points before you callbrm_data(). See the "Preprocessing"section for details.

missing

Character of length 1, name of an optional variablein a simulated dataset to indicate which outcome values should be missing.Set toNULL to omit.

reference_group

Atomic value of length 1, Level of thegroupcolumn to indicate the control group.Example possibilities from clinical trial datasets include"Placebo","PLACEBO","PBO","PLB","CONTROL","CTRL","REFERENCE", and"REF".reference_group only applies to the post-processing that happensin functions likebrm_marginal_draws() downstream of the model.It does not control the fixed effect mapping in themodel matrix thatbrms derives from the formula frombrm_formula().

reference_subgroup

Atomic value of length 1,level of thesubgroup columnto use as a reference for pairwise differences in when computingmarginal means downstream of the model.It does not control the fixed effect mapping in themodel matrix thatbrms derives from the formula frombrm_formula().

reference_time

Atomic value of length 1 orNULL,level of thetime column to indicate the baseline time point.Leave asNULL if there is no baseline or baseline is not includedindata[[time]].

Ifreference_time is notNULL, thenbrm_marginal_draws() willcalculate change from baseline, and it will calculate treatmentdifferences as differences between change-from-baseline values.Ifreference_time is notNULL, thenbrm_marginal_draws() willnot calculate change from baseline, and it will calculate treatmentdifferences as differences between response values.

Note:reference_time only applies to the post-processing that happensin functions likebrm_marginal_draws() downstream of the model.It does not control the fixed effect mapping in themodel matrix thatbrms derives from the formula frombrm_formula().

role

Deprecated as unnecessary on 2024-07-11 (version 1.0.1.9007).Usereference_time to supply a baseline time point value if it exists.

level_baseline

Deprecated on 2024-01-11 (version 0.2.0.9002).Usereference_time instead.

level_control

Deprecated on 2024-01-11 (version 0.2.0.9002).Usereference_group instead.

Value

A classed tibble with attributes which denote features ofthe data such as the treatment group and discrete time variables.

Preprocessing

The preprocessing steps inbrm_data() are as follows:

Separation string

Post-processing inbrm_marginal_draws() names each of thegroup-by-time marginal means with the delimiting character stringfromSys.getenv("BRM_SEP", unset = "|"). Neither the column namesnor element names of the group and time variables can containthis string. To set a custom string yourself, useSys.setenv(BRM_SEP = "YOUR_CUSTOM_STRING").

See Also

Other data:brm_data_change(),brm_data_chronologize()

Examples

set.seed(0)data <- brm_simulate_simple()$datacolnames(data) <- paste0("col_", colnames(data))databrm_data(  data = data,  outcome = "col_response",  group = "col_group",  time = "col_time",  patient = "col_patient",  reference_group = "group_1",  reference_time = "time_1")

Convert to change from baseline.

Description

Convert a dataset from raw response to change from baseline.

Usage

brm_data_change(data, name_change = "change", name_baseline = "baseline")

Arguments

data

A classedtibble (e.g. frombrm_data()) with raw responseas the outcome variable and no baseline time point stored in theattributes.

name_change

Character of length 1, name of the new outcome columnfor change from baseline.

name_baseline

Character of length 1, name of the new column forthe original baseline response.

Value

A classedtibble with change from baseline as the outcome variableand the internal attributes modified accordingly. A special baselinecolumn is also created, and the original raw response column is removed.The new baseline column is comprised of the elements of the responsevariable corresponding to thereference_time argument ofbrm_data().

If there is a column to denote missing values for simulation purposes,e.g. the"missing" column generated bybrm_simulate_outline(),then missing baseline values are propagated accordingly such thatchange from baseline will be missing if either the post-baseline responseis missing or the baseline response is missing.

See Also

Other data:brm_data(),brm_data_chronologize()

Examples

set.seed(0)data <- brm_data(  data = dplyr::rename(brm_simulate_simple()$data, y_values = response),  outcome = "y_values",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")dataattr(data, "brm_outcome")attr(data, "brm_baseline")attr(data, "brm_reference_time")changed <- brm_data_change(data = data, name_change = "delta")changedattr(changed, "brm_outcome")attr(changed, "brm_baseline")attr(data, "brm_reference_time")

Chronologize a dataset

Description

Convert the discrete time variable into an ordered factor.

Usage

brm_data_chronologize(  data,  order = NULL,  levels = NULL,  time = attr(data, "brm_time"))

Arguments

data

Data frame or tibble with longitudinal data.

order

Optional character string with the name of a variable inthe data for ordering the time variable.Eitherorder orlevels must be supplied, but not both together.Iforder is supplied,the levels ofdata[[order]] must have a 1:1 correspondence withthose ofdata[[time]], andsort(unique(data[[order]])) mustreflect the desired order of the levels ofdata[[time]]. For example,suppose you have a CDISC dataset with categorical time variableAVISITand integer variableAVISITN. Then,brm_data_chronologize(time = "AVISIT", order = "AVISITN") will turnAVISIT into an ordered factor with levels that respect the orderinginAVISITN.

levels

Optional character vector of levels ofdata[[time]]in chronological order. Used to turndata[[time]] into anordered factor.Eitherorder orlevels must be supplied, but not both together.

time

Character string with the name of the discrete timevariable in the data. This is the variable thatbrm_data_chronologize()turns into an ordered factor. It needs to be specified explicitlyif and only if thedata argument was not produced by a call tobrm_data().

Details

Most MMRMs should use an ordered factor for thetime columnin the data. This way, individual time points are treated asdistinct factor levels for the purposes of fixed effect parameterizations(see the "Contrasts" section), and the explicit ordering ensuresthat informative prior archetypes and ARMA-like correlation structuresare expressed correctly. Without the ordering, problems can arise whencharacter vectors are sorted: e.g. ifAVISIT has levels⁠"VISIT1", "VISIT2", ..., "VISIT10"⁠, thenbrms will mistake thethe order of scheduled study visits to be⁠"VISIT1", "VISIT10", "VISIT2", ...⁠, which is not chronological.

You can easily turnthe time variable into an ordered factor usingbrm_data_chronologize(). Either supply an explicit character vectorof chronologically-ordered factor levels in thelevels argument,or supply the name of a time-ordered variable in theorder argument.

brm_data_chronologize() can be called either before or just afterbrm_data(), but in the former case, the discrete time variableneeds to be specified explicitly intime argument. And in the latter,brm_data_chronologize() must be called before any of the informativeprior archetype functions such asbrm_archetype_successive_cells().

Value

A data frame with the time column as an ordered factor.

Contrasts

Ordinarily, ordered factors automatically use polynomial contrasts fromcontr.poly(). This is undesirable for MMRMs, so if the time variableis an ordered factor, thenbrm_data()manually setscontrasts(data[[time]]) to a set of treatment contrastsusingcontr.treatment(). If you prefer different contrasts, pleasemanually setcontrasts(data[[time]]) to something else aftercallingbrm_data().

See Also

Other data:brm_data(),brm_data_change()

Examples

data <- brm_simulate_outline(n_time = 12, n_patient = 4)data$AVISIT <- gsub("_0", "_", data$time)data$AVISITN <- as.integer(gsub("time_", "", data$time))data[, c("AVISIT", "AVISITN")]sort(unique(data$AVISIT)) # wrong orderdata1 <- brm_data_chronologize(data, time = "AVISIT", order = "AVISITN")sort(unique(data1$AVISIT)) # correct orderlevels <- paste0("time_", seq_len(12))data2 <- brm_data_chronologize(data, time = "AVISIT", levels = levels)sort(unique(data2$AVISIT)) # correct order

Model formula

Description

Build a model formula for an MMRM, either for a genericbrm_data() dataset or an informative prior archetype.

Usage

brm_formula(  data,  model_missing_outcomes = FALSE,  check_rank = TRUE,  sigma = brms.mmrm::brm_formula_sigma(data = data, check_rank = check_rank),  correlation = "unstructured",  autoregressive_order = 1L,  moving_average_order = 1L,  residual_covariance_arma_estimation = FALSE,  ...)## Default S3 method:brm_formula(  data,  model_missing_outcomes = FALSE,  check_rank = TRUE,  sigma = brms.mmrm::brm_formula_sigma(data = data, check_rank = check_rank),  correlation = "unstructured",  autoregressive_order = 1L,  moving_average_order = 1L,  residual_covariance_arma_estimation = FALSE,  intercept = TRUE,  baseline = !is.null(attr(data, "brm_baseline")),  baseline_subgroup = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_subgroup_time = !is.null(attr(data, "brm_baseline")) && !is.null(attr(data,    "brm_subgroup")),  baseline_time = !is.null(attr(data, "brm_baseline")),  covariates = TRUE,  group = TRUE,  group_subgroup = !is.null(attr(data, "brm_subgroup")),  group_subgroup_time = !is.null(attr(data, "brm_subgroup")),  group_time = TRUE,  subgroup = !is.null(attr(data, "brm_subgroup")),  subgroup_time = !is.null(attr(data, "brm_subgroup")),  time = TRUE,  center = TRUE,  ...,  effect_baseline = NULL,  effect_group = NULL,  effect_time = NULL,  interaction_baseline = NULL,  interaction_group = NULL)## S3 method for class 'brms_mmrm_archetype'brm_formula(  data,  model_missing_outcomes = FALSE,  check_rank = TRUE,  sigma = brms.mmrm::brm_formula_sigma(data = data, check_rank = check_rank),  correlation = "unstructured",  autoregressive_order = 1L,  moving_average_order = 1L,  residual_covariance_arma_estimation = FALSE,  ...,  warn_ignored = TRUE)

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

model_missing_outcomes

Logical of length 1,TRUEto impute missing outcomes during model fitting as described in the"Imputation during model fitting" section ofhttps://paulbuerkner.com/brms/articles/brms_missings.html.Specifically, if the outcome variable isy, then the formula willbegin withy | mi() ~ ... instead of simplyy ~ ....Set toFALSE (default) to forgo this kind of imputationand discard missing observations from the datajust prior to fitting the model insidebrm_model(). Seehttps://opensource.nibr.com/bamdd/src/02h_mmrm.html#what-estimand-does-mmrm-address #nolintto understand the standard assumptions and decisions regarding MMRMsand missing outcomes.

check_rank

TRUE to check the rank of the model matrix andthrow an error if rank deficiency is detected.FALSE to skipthis check. Rank-deficient models may have non-identifiableparameters and it is recommended to choose a full-rank mapping.

sigma

A formula produced bybrm_formula_sigma().The formula is a base R formula with S3 class"brms_mmrm_formula_sigma", and it controlsthe parameterization of the residual standard deviationssigma.

correlation

Character of length 1, name of the correlationstructure. The correlation matrix is a square⁠T x T⁠ matrix, whereT is the number of discrete time points in the data.This matrix describes the correlations between time points in the samepatient, as modeled in the residuals. Different patients are modeledas independent. Thecorrelation argument controls how this matrixis parameterized, and the choices given bybrms are listed athttps://paulbuerkner.com/brms/reference/autocor-terms.html,and the choice is ultimately encoded in the main body of theoutput formula through terms likeunstru() andarma(), someof which are configurable through argumentsautoregressive_order,moving_average_order, andresidual_covariance_arma_estimation ofbrm_formula().Choices inbrms.mmrm:

autoregressive_order

Nonnegative integer,autoregressive order for the"autoregressive_moving_average"and"autoregressive" correlation structures.

moving_average_order

Nonnegative integer,moving average order for the"autoregressive_moving_average"and"moving_average" correlation structures.

residual_covariance_arma_estimation

TRUE orFALSE,whether to estimate ARMA effects using residual covariance matrices.Directly supplied to thecov argument inbrms for"autoregressive_moving_average","autoregressive", and"moving_average" correlation structures. C.f.https://paulbuerkner.com/brms/reference/arma.html.

...

Named arguments to specificbrm_formula() methods.

intercept

Logical of length 1.TRUE (default) to include an intercept,FALSE to omit.

baseline

Logical of length 1.TRUE to include an additive effect for baselineresponse,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_subgroup

Logical of length 1.

baseline_subgroup_time

Logical of length 1.TRUE to include baseline-by-subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared baselineand subgroup variables in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

baseline_time

Logical of length 1.TRUE to include baseline-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a baselinevariable in the dataset.Ignored for informative prior archetypes.For informative prior archetypes, this option should be set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

covariates

Logical of length 1.TRUE (default) to include any additive covariates declared withthecovariates argument ofbrm_data(),FALSE to omit.For informative prior archetypes, this option is set infunctions likebrm_archetype_successive_cells() rather than inbrm_formula() in order to make sure columns are appropriatelycentered and the underlying model matrix has full rank.

group

Logical of length 1.TRUE (default) to include additive effects fortreatment groups,FALSE to omit.

group_subgroup

Logical of length 1.TRUE to include group-by-subgroup interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a subgroupvariable in the dataset.

group_subgroup_time

Logical of length 1.TRUE to include group-by-subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a subgroupvariable in the dataset.

group_time

Logical of length 1.TRUE (default) to include group-by-time interaction,FALSE to omit.

subgroup

Logical of length 1.TRUE to include additive fixed effects for subgroup levels,FALSE to omit.Default isTRUE ifbrm_data() previously declared a subgroupvariable in the dataset.

subgroup_time

Logical of length 1.TRUE to include subgroup-by-time interaction,FALSE to omit.Default isTRUE ifbrm_data() previously declared a subgroupvariable in the dataset.

time

Logical of length 1.TRUE (default) to include a additive effect for discrete time,FALSE to omit.

center

TRUE to center the columns of the model matrix beforefitting the model if the model formula includes an interceptterm controlled bybrms.FALSE to skip centering. Centering usuallyleads to more computationally efficient sampling in the presenceof an intercept, but it changesthe interpretation of the intercept parameter if included in the model(as explained in the help file ofbrms::brmsformula()).Informative prior archetypes always usecenter = FALSEand use an intercept not controlled bybrms.mmrm to ensure theintercept parameter is interpretable and compatible withuser-defined priors.

effect_baseline

Deprecated on 2024-01-16 (version 0.0.2.9002).Usebaseline instead.

effect_group

Deprecated on 2024-01-16 (version 0.0.2.9002).Usegroup instead.

effect_time

Deprecated on 2024-01-16 (version 0.0.2.9002).Usetime instead.

interaction_baseline

Deprecated on 2024-01-16 (version 0.0.2.9002).Usebaseline_time instead.

interaction_group

Deprecated on 2024-01-16 (version 0.0.2.9002).Usegroup_time instead.

warn_ignored

Set toTRUEto throw a warning if ignored arguments are specified,FALSE otherwise.

Value

An object of class"brmsformula" returned frombrms::brmsformula(). It contains the fixed effect mapping,correlation structure, and residual variance structure.

brm_data() formulas

For abrm_data() dataset,brm_formula() builds an R formula for an MMRM based onthe details in the data and your choice of mapping.Customize your mapping by toggling on or offthe variousTRUE/FALSE arguments ofbrm_formula(),such asintercept,baseline, andgroup_time.All plausible additive effects, two-way interactions, andthree-way interactions can be specified. The following interactionsare not supported:

Formulas for informative prior archetypes

Functions likebrm_archetype_successive_cells()tailor datasets to informative prior archetypes. For these specializedtailored datasets,brm_formula() works differently. It still appliesthe variance and correlation structure of your choosing, and it stilllets you choose whether to adjust for nuisance covariates,but it no longer lets you toggle on/off individual terms in the model,such asintercept,baseline, orgroup. Instead, to ensure thecorrect interpretation of the parameters,brm_formula() usesthe⁠x_*⁠ and⁠nuisance_*⁠ columns generated bybrm_archetype_successive_cells( prefix_interest = "x_", prefix_nuisance = "nuisance_").

Parameterization

For a formula on abrm_data() dataset,the formula is not the only factorthat determines the fixed effect mapping.The ordering of the categorical variables in the data,as well as thecontrast option in R, affect theconstruction of the model matrix. To see the modelmatrix that will ultimately be used inbrm_model(),runbrms::make_standata() and examine theX elementof the returned list. See the examples below for ademonstration.

See Also

Other models:brm_formula_sigma(),brm_model()

Examples

set.seed(0)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")brm_formula(data)brm_formula(data = data, intercept = FALSE, baseline = FALSE)formula <- brm_formula(  data = data,  intercept = FALSE,  baseline = FALSE,  group = FALSE)formula# Standard deviations of residuals are distributional parameters that can# regress on variables in the data.homogeneous <- brm_formula_sigma(data, time = FALSE)by_group <- brm_formula_sigma(data, group = TRUE, intercept = TRUE)homogeneousby_groupbrm_formula(data, sigma = homogeneous)brm_formula(data, sigma = by_group)# Optional: set the contrast option, which determines the model matrix.options(contrasts = c(unordered = "contr.SAS", ordered = "contr.poly"))# See the fixed effect mapping you get from the data:head(brms::make_standata(formula = formula, data = data)$X)# Specify a different contrast method to use an alternative# mapping when fitting the model with brm_model():options(  contrasts = c(unordered = "contr.treatment", ordered = "contr.poly"))# different model matrix than before:head(brms::make_standata(formula = formula, data = data)$X)# Formula on an informative prior archetype:data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = "biomarker3",    levels = c("present", "absent")  )archetype <- brm_archetype_successive_cells(data)formula <- brm_formula(data = archetype)formula

Formula for standard deviation parameters

Description

Parameterize standard deviations usinga formula for thesigma argument ofbrm_formula().

Usage

brm_formula_sigma(  data,  check_rank = TRUE,  intercept = FALSE,  baseline = FALSE,  baseline_subgroup = FALSE,  baseline_subgroup_time = FALSE,  baseline_time = FALSE,  covariates = FALSE,  group = FALSE,  group_subgroup = FALSE,  group_subgroup_time = FALSE,  group_time = FALSE,  subgroup = FALSE,  subgroup_time = FALSE,  time = TRUE)

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

check_rank

TRUE to check the rank of the model matrixforsigma and throw an error if rank deficiency is detected.FALSE to skip this check.Rank-deficiency may causesigma to be non-identifiable,may prevent the MCMC from converging.

intercept

Logical of length 1.TRUE (default) to include an intercept,FALSE to omit.

baseline

Logical of length 1.TRUE to include an additive effect for baselineresponse,FALSE to omit.IfTRUE, then effect size will be omitted from the output ofbrm_marginal_draws().

baseline_subgroup

Logical of length 1.

baseline_subgroup_time

Logical of length 1.TRUE to include baseline-by-subgroup-by-time interaction,FALSE to omit.IfTRUE, then effect size will be omitted from the output ofbrm_marginal_draws().

baseline_time

Logical of length 1.TRUE to include baseline-by-time interaction,FALSE to omit.IfTRUE, then effect size will be omitted from the output ofbrm_marginal_draws().

covariates

Logical of length 1.TRUE (default) to include any additive covariates declared withthecovariates argument ofbrm_data(),FALSE to omit.IfTRUE, then effect size will be omitted from the output ofbrm_marginal_draws().

group

Logical of length 1.TRUE (default) to include additive effects fortreatment groups,FALSE to omit.

group_subgroup

Logical of length 1.TRUE to include group-by-subgroup interaction,FALSE to omit.

group_subgroup_time

Logical of length 1.TRUE to include group-by-subgroup-by-time interaction,FALSE to omit.

group_time

Logical of length 1.

subgroup

Logical of length 1.TRUE to include additive fixed effects for subgroup levels,FALSE to omit.

subgroup_time

Logical of length 1.TRUE to include subgroup-by-time interaction,FALSE to omit.

time

Logical of length 1.

Details

Inbrms, the standard deviations of the residuals aremodeled through a parameter vector calledsigma.brms.mmrmalways treatssigma as a distributional parameter(https://paulbuerkner.com/brms/articles/brms_distreg.html).brm_formula_sigma() lets you control the parameterization ofsigma.The output ofbrm_formula_sigma() serves as input to thesigmaargument ofbrm_formula().

The defaultsigma formula issigma ~ 0 + time, wheretimeis the discrete time variable in the data. This is the usualheterogeneous variance structure which declaresone standard deviation parameter for each time point in the data.Alternatively, you could writebrm_formula_sigma(data, intercept = TRUE, time = FALSE).This will producesigma ~ 1, which yields a single scalar variance(a structure termed "homogeneous variance").

With arguments likebaseline andcovariates, you canspecify extremely complicated variance structures. However,if baseline or covariates are used, then the output ofbrm_marginal_draws() omit effect size due to the statisticalchallenges of calculating marginal means of draws ofsigmafor this uncommon scenario.

Value

A base R formula with S3 class"brms_mmrm_formula_sigma".This formula controls the parameterization ofsigma, the linear-scalebrms distributional parameters which represent standard deviations.

See Also

Other models:brm_formula(),brm_model()

Examples

set.seed(0)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")homogeneous <- brm_formula_sigma(data, time = FALSE, intercept = TRUE)by_group <- brm_formula_sigma(data, group = TRUE, intercept = TRUE)homogeneousby_groupbrm_formula(data, sigma = homogeneous)brm_formula(data, sigma = by_group)

Marginal summaries of the data.

Description

Marginal summaries of the data.

Usage

brm_marginal_data(  data,  level = 0.95,  use_subgroup = !is.null(attr(data, "brm_subgroup")))

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

level

Numeric of length 1 from 0 to 1, level of the confidenceintervals.

use_subgroup

Logical of length 1, whether to summarize the data byeach subgroup level.

Value

A tibble with one row per summary statistic and the followingcolumns:

Thestatistic column has the following possible values:

See Also

Other marginals:brm_marginal_draws(),brm_marginal_draws_average(),brm_marginal_grid(),brm_marginal_probabilities(),brm_marginal_summaries()

Examples

set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")brm_marginal_data(data = data)

MCMC draws from the marginal posterior of an MMRM

Description

Get marginal posterior draws from a fitted MMRM.

Usage

brm_marginal_draws(  model,  data = model$brms.mmrm_data,  formula = model$brms.mmrm_formula,  transform = brms.mmrm::brm_transform_marginal(data = data, formula = formula,    average_within_subgroup = average_within_subgroup),  effect_size = attr(formula, "brm_allow_effect_size"),  average_within_subgroup = NULL,  use_subgroup = NULL,  control = NULL,  baseline = NULL)

Arguments

model

A fitted model object frombrm_model().

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

formula

An object of class"brmsformula" frombrm_formula()orbrms::brmsformula(). Should include the full mappingof the model, including fixed effects, residual correlation,and heterogeneity in the discrete-time-specific residual variancecomponents.

transform

Matrix with one row per marginal mean and one columnper model parameter.brm_marginal_draws() uses this matrixto map posterior draws of model parameters to posterior draws ofmarginal means using matrix multiplication. Please usebrm_transform_marginal() to compute this matrix and then modifyonly if necessary. See the methods vignettes for details on thismatrix, as well as howbrms.mmrm computes marginal means moregenerally.

effect_size

Logical,TRUE to derive posterior samplesof effect size (treatment effect divided by residual standarddeviation).FALSE to omit.brms.mmrm does not supporteffect size when baseline or covariates are includedin thebrm_formula_sigma() formula. Ifeffect_size isTRUEin this case, thenbrm_marginal_draws() will automaticallyomit effect size and throw an informative warning.

average_within_subgroup

TRUE,FALSE, orNULL to controlwhether nuisance parameters are averaged within subgroup levelsinbrm_transform_marginal(). Ignored if thetransform argumentis manually supplied by the user. See the help page ofbrm_transform_marginal() for details on theaverage_within_subgroup argument.

use_subgroup

Deprecated. No longer used.brm_marginal_draws()no longer marginalizes over the subgroup declaredinbrm_data(). To marginalize over the subgroup, declarethat variable incovariates instead.

control

Deprecated. Set the control group level inbrm_data().

baseline

Deprecated. Set the control group level inbrm_data().

Value

A named list of tibbles of MCMC draws of the marginal posteriordistribution of each treatment group and time point. These marginalsare also subgroup-specific ifbrm_formula() included fixed effectsthat use thesubgroup variable originally declared inbrm_data().In each tibble, there is 1 row per posterior sample and one column foreach type of marginal distribution (i.e. each combination of treatmentgroup and discrete time point. The specifictibbles in the returnedlist are described below:

Baseline

The returned values frombrm_marginal_draws()depend on whether a baseline time pointwas declared through thereference_time argument ofbrm_data().Ifreference_time was notNULL, thenbrm_marginal_draws() willcalculate change from baseline, and it will calculate treatmentdifferences as differences between change-from-baseline values.Ifreference_time was notNULL, thenbrm_marginal_draws() willnot calculate change from baseline, and it will calculate treatmentdifferences as differences between response values.

Separation string

Post-processing inbrm_marginal_draws() names each of thegroup-by-time marginal means with the delimiting character stringfromSys.getenv("BRM_SEP", unset = "|"). Neither the column namesnor element names of the group and time variables can containthis string. To set a custom string yourself, useSys.setenv(BRM_SEP = "YOUR_CUSTOM_STRING").

See Also

Other marginals:brm_marginal_data(),brm_marginal_draws_average(),brm_marginal_grid(),brm_marginal_probabilities(),brm_marginal_summaries()

Examples

if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = data,        formula = formula,        chains = 1,        iter = 100,        refresh = 0      )    )  ))brm_marginal_draws(data = data, formula = formula, model = model)}

Average marginal MCMC draws across time points.

Description

Simple un-weighted arithmetic mean ofmarginal MCMC draws across time points.

Usage

brm_marginal_draws_average(draws, data, times = NULL, label = "average")

Arguments

draws

List of posterior draws frombrm_marginal_draws().

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

times

Character vector of discrete time point levelsover which to average the MCMC samples within treatment group levels.Set toNULL to average across all time points. Levels are automaticallysanitized withmake.names(unique = FALSE, allow_ = TRUE) to ensureagreement withbrms variable names in downstream computations.

label

Character of length 1, time point label for the averages.Automatically sanitized withmake.names(unique = FALSE, allow_ = TRUE).Must not conflict with any existing time point labels in the dataafter the label and time points are sanitized.

Value

A named list of tibbles of MCMC draws of the marginal posteriordistribution of each treatment group and time point(or group-by-subgroup-by-time, if applicable).Seebrm_marginal_draws() for the full details of the return value.The only difference is thatbrm_marginal_draws_average() returnsa single pseudo-time-point to represent the average acrossmultiple real time points.

Separation string

Post-processing inbrm_marginal_draws() names each of thegroup-by-time marginal means with the delimiting character stringfromSys.getenv("BRM_SEP", unset = "|"). Neither the column namesnor element names of the group and time variables can containthis string. To set a custom string yourself, useSys.setenv(BRM_SEP = "YOUR_CUSTOM_STRING").

See Also

Other marginals:brm_marginal_data(),brm_marginal_draws(),brm_marginal_grid(),brm_marginal_probabilities(),brm_marginal_summaries()

Examples

if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = data,        formula = formula,        chains = 1,        iter = 100,        refresh = 0      )    )  ))draws <- brm_marginal_draws(data = data, formula = formula, model = model)brm_marginal_draws_average(draws = draws, data = data)brm_marginal_draws_average(  draws = draws,  data = data,  times = c("time_1", "time_2"),  label = "mean")}

Marginal names grid.

Description

Describe the column names of the data frames outputbybrm_marginal_draws().

Usage

brm_marginal_grid(data, formula)

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

formula

An object of class"brmsformula" frombrm_formula()orbrms::brmsformula(). Should include the full mappingof the model, including fixed effects, residual correlation,and heterogeneity in the discrete-time-specific residual variancecomponents.

Details

Useful for creating custom posterior summaries from the draws.

Value

A data frame with aname column with the names of columns ofdata frames inbrm_marginal_draws(), along with metadata todescribe which groups, subgroups, and time points those columnscorrespond to.

See Also

Other marginals:brm_marginal_data(),brm_marginal_draws(),brm_marginal_draws_average(),brm_marginal_probabilities(),brm_marginal_summaries()

Examples

data <- brm_simulate_outline()brm_marginal_grid(data, brm_formula(data))data <- brm_simulate_outline(n_subgroup = 2L)brm_marginal_grid(data, brm_formula(data))

Marginal probabilities on the treatment effect for an MMRM.

Description

Marginal probabilities on the treatment effect for an MMRM.

Usage

brm_marginal_probabilities(draws, direction = "greater", threshold = 0)

Arguments

draws

Posterior draws of the marginal posteriorobtained frombrm_marginal_draws().

direction

Character vector of the same length asthreshold."greater" to compute the marginal posterior probability that thetreatment effect is greater than the threshold,"less" to compute the marginal posterior probability that thetreatment effect is less than the threshold.Each elementdirection[i] corresponds tothreshold[i]for alli from 1 tolength(direction).

threshold

Numeric vector of the same length asdirection,treatment effect threshold for computing posterior probabilities.Each elementdirection[i] corresponds tothreshold[i] foralli from 1 tolength(direction).

Value

A tibble of probabilities of the form⁠Prob(treatment effect > threshold | data)⁠ and/or⁠Prob(treatment effect < threshold | data)⁠. It has one row perprobability and the following columns:*group: treatment group.*subgroup: subgroup level, if applicable.*time: discrete time point,*direction: direction of the comparison in the marginal probability:"greater" for>,"less" for<*threshold: treatment effect threshold in the probability statement.*value: numeric value of the estimate of the probability.

See Also

Other marginals:brm_marginal_data(),brm_marginal_draws(),brm_marginal_draws_average(),brm_marginal_grid(),brm_marginal_summaries()

Examples

if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = data,        formula = formula,        chains = 1,        iter = 100,        refresh = 0      )    )  ))draws <- brm_marginal_draws(data = data, formula = formula, model = model)brm_marginal_probabilities(draws, direction = "greater", threshold = 0)}

Summary statistics of the marginal posterior of an MMRM.

Description

Summary statistics of the marginal posterior of an MMRM.

Usage

brm_marginal_summaries(draws, level = 0.95)

Arguments

draws

Posterior draws of the marginal posteriorobtained frombrm_marginal_draws().

level

Numeric of length 1 between 0 and 1, credible levelfor the credible intervals.

Value

A tibble with one row per summary statistic and the followingcolumns:

See Also

Other marginals:brm_marginal_data(),brm_marginal_draws(),brm_marginal_draws_average(),brm_marginal_grid(),brm_marginal_probabilities()

Examples

if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = data,        formula = formula,        chains = 1,        iter = 100,        refresh = 0      )    )  ))draws <- brm_marginal_draws(data = data, formula = formula, model = model)suppressWarnings(brm_marginal_summaries(draws))}

Fit an MMRM.

Description

Fit an MMRM model usingbrms.

Usage

brm_model(  data,  formula,  ...,  prior = NULL,  family = brms::brmsfamily(family = "gaussian"),  imputed = NULL)

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().Unless you suppliedmodel_missing_outcomes = TRUE inbrm_formula(),brm_model() automatically rows with missing outcomesjust prior to fitting the model withbrms::brm().Thebrms.mmrm_data attributein the output object is always the version of the data prior toremoving these rows. See thedata element of the returnedbrmsobject for the final data actually supplied to the model.

If you supply a non-NULL value for theimputedargument, then thedata argument is ignored and the MMRM is fitsuccessively to each dataset inimputed usingbrms::brm_multiple().Posterior draws are combined automatically for downstream post-processingunless you setcombine = FALSE inbrm_model().

formula

An object of class"brmsformula" frombrm_formula()orbrms::brmsformula(). Should include the full mappingof the model, including fixed effects, residual correlation,and heterogeneity in the discrete-time-specific residual variancecomponents.

...

Arguments tobrms::brm() orbrms::brm_multiple()other thandata,formula,prior, andfamily.

prior

EitherNULL for default priorsor a"brmsprior" object frombrms::prior().

family

Abrms family object generated bybrms::brmsfamily().Must fit a continuous outcome variable and have the identity link.

imputed

EitherNULL (default), list ofdatasets generated with multiple imputation, or a"mids" objectfrom themice package. Therbmi package may offer a more appropriatemethod for imputation for MMRMs thanmice. It is your responsibilityto choose an imputation method appropriate for the data and model.

If notNULL, then the MMRM is fitsuccessively to each dataset inimputed usingbrms::brm_multiple().Posterior draws are combined automatically for downstream post-processingunless you setcombine = FALSE inbrm_model(), so everything atthe level ofbrm_marginal_draws() will be exactly the same asa non-imputation workflow.

Even if you supplyimputed, please also supply the originalnon-imputed dataset in thedata argument to help withdownstream post-processing.

Value

A fitted model object frombrms, with new list elementsbrms.mmrm_data andbrms.mmrm_formula to capture the dataand formula supplied tobrm_model(). See the explanation of thedata argument for how the data is handled and how it relatesto the data returned in thebrms.mmrm_data attribute.

Parameterization

For a formula on abrm_data() dataset,the formula is not the only factorthat determines the fixed effect mapping.The ordering of the categorical variables in the data,as well as thecontrast option in R, affect theconstruction of the model matrix. To see the modelmatrix that will ultimately be used inbrm_model(),runbrms::make_standata() and examine theX elementof the returned list. See the examples below for ademonstration.

See Also

Other models:brm_formula(),brm_formula_sigma()

Examples

if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)# Optional: set the contrast option, which determines the model matrix.options(contrasts = c(unordered = "contr.SAS", ordered = "contr.poly"))# See the fixed effect mapping you get from the data:head(brms::make_standata(formula = formula, data = data)$X)# Specify a different contrast method to use an alternative# mapping when fitting the model with brm_model():options(  contrasts = c(unordered = "contr.treatment", ordered = "contr.poly"))# different model matrix than before:head(brms::make_standata(formula = formula, data = data)$X)tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = data,        formula = formula,        chains = 1,        iter = 100,        refresh = 0      )    )  ))# The output is a brms model fit object with added list# elements "brms.mmrm_data" and "brms.mmrm_formula" to track the dataset# and formula used to fit the model.model$brms.mmrm_datamodel$brms.mmrm_formula# Otherwise, the fitted model object acts exactly like a brms fitted model.suppressWarnings(print(model))brms::prior_summary(model)}

Visually compare the marginals of multiple models and/or datasets.

Description

Visually compare the marginals of multiple modelsand/or datasets.

Usage

brm_plot_compare(  ...,  marginal = "response",  compare = "source",  axis = "time",  facet = c("group", "subgroup"))

Arguments

...

Namedtibbles of marginals posterior summariesfrombrm_marginal_summaries() and/orbrm_marginal_data().

marginal

Character of length 1, which kind of marginalto visualize. Must be a value in themarginal column of the suppliedtibbles in the... argument.Only applies to MCMC output, the data is always on the scale of theresponse variable.

compare

Character of length 1 identifying the variable to displayusing back-to-back interval plots of different colors. This isthe primary comparison of interest. Must be one of"source" (the source of the marginal summaries,e.g. a model or dataset),"time" or"group"(in the non-subgroup case). Can also be"subgroup"if all the marginal summaries are subgroup-specific.The value must not be inaxis orfacet.

axis

Character of length 1 identifying the quantity to puton the horizontal axis. Must be be one of"source"(the source of the marginal summaries,e.g. a model or dataset),"time",or"group" (in the non-subgroup case). If the marginalsare subgroup-specific, thenaxis can also be"subgroup".The value must not be incompare orfacet.

facet

Character vector of length 1 or 2 with quantities togenerate facets. Each element must be"source"(the source of the marginal summaries,e.g. a model or dataset),"time","group",or"subgroup", andc(axis, facet) must all have unique elements."subgroup" is automatically removed if not all the marginal summarieshave a subgroup column. Iffacet has length 1, then faceting is wrapped.Iffacet has length 2, then faceting is in a grid,and the first element is horizontal facet.

Details

By default,brm_plot_compare() compares multiple modelsand/or datasets side-by-side. Thecompare argument selects the primarycomparison of interest, and argumentsaxis andfacet controlthe arrangement of various other components of the plot.The subgroup variable is automatically included if and only ifall the supplied marginal summaries have a subgroup column.

Value

Aggplot object.

See Also

Other visualization:brm_plot_draws()

Examples

if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = data,        formula = formula,        chains = 1,        iter = 100,        refresh = 0      )    )  ))draws <- brm_marginal_draws(data = data, formula = formula, model = model)suppressWarnings(summaries_draws <- brm_marginal_summaries(draws))summaries_data <- brm_marginal_data(data)brm_plot_compare(  model1 = summaries_draws,  model2 = summaries_draws,  data = summaries_data)brm_plot_compare(  model1 = summaries_draws,  model2 = summaries_draws,  marginal = "difference")}

Visualize posterior draws of marginals.

Description

Visualize posterior draws of marginals.

Usage

brm_plot_draws(draws, axis = "time", facet = c("group", "subgroup"))

Arguments

draws

A data frame of draws from an element ofthe output list ofbrm_marginal_summaries().

axis

Character of length 1 identifying the quantity to puton the horizontal axis. Must be be one of"time" or"group" ifthe marginal summaries are not subgroup-specific. If the marginalsare subgroup-specific, thenaxis must be one of"time","group", or"subgroup".

facet

Character vector of length 1 or 2 with quantities togenerate facets. Each element must be"time","group",or"subgroup", andc(axis, facet) must all have unique elements."subgroup" is automatically removed if the marginals have nosubgroup. Iffacet has length 1, then faceting is wrapped.Iffacet has length 2, then faceting is in a grid,and the first element is horizontal facet.

Value

Aggplot object.

See Also

Other visualization:brm_plot_compare()

Examples

if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      model <- brm_model(        data = data,        formula = formula,        chains = 1,        iter = 100,        refresh = 0      )    )  ))draws <- brm_marginal_draws(data = data, formula = formula, model = model)brm_plot_draws(draws = draws$difference_time)}

Informative priors for fixed effects in archetypes

Description

Create abrms prior for fixed effects in an archetype.

Usage

brm_prior_archetype(label, archetype)

Arguments

label

A data frame with one row per model parameter in thearchetype and columns to indicate the mapping between priorsand labels. Generate usingbrm_prior_label() or manually.See the examples and the informative prior archetypes vignettefor details.

archetype

An informative prior archetype generated by a functionlikebrm_archetype_successive_cells().

Value

Abrms prior object that you can supply to thepriorargument ofbrm_model().

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other priors:brm_prior_label(),brm_prior_simple(),brm_prior_template()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 3,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )archetype <- brm_archetype_successive_cells(data)dplyr::distinct(data, group, time)prior <- NULL |>  brm_prior_label("normal(1, 1)", group = "group_1", time = "time_1") |>  brm_prior_label("normal(1, 2)", group = "group_1", time = "time_2") |>  brm_prior_label("normal(1, 3)", group = "group_1", time = "time_3") |>  brm_prior_label("normal(2, 1)", group = "group_2", time = "time_1") |>  brm_prior_label("normal(2, 2)", group = "group_2", time = "time_2") |>  brm_prior_label("normal(2, 3)", group = "group_2", time = "time_3") |>  brm_prior_archetype(archetype = archetype)priorclass(prior)

Label a prior with levels in the data.

Description

Label an informative prior for a parameterusing a collection of levels in the data.

Usage

brm_prior_label(label = NULL, code, group, subgroup = NULL, time)

Arguments

label

Atibble with the prior labeling scheme so far,with one row per model parameter and columns for theStan code, treatment group, subgroup, and discrete time pointof each parameter.

code

Character of length 1, Stan code for the prior. Could bea string like"normal(1, 2.2)". The full set of priors is givenin the Stan Function Reference athttps://mc-stan.org/docs/functions-reference/ in the"Unbounded Continuous Distributions" section.See the documentationbrms::set_prior() for more details.

group

Value of length 1, level of the treatment group columnin the data to label the prior. The treatment group columnis the one you identified with thegroup argument ofbrm_data().

subgroup

Value of length 1, level of the subgroup columnin the data to label the prior. The subgroup columnis the one you identified with thesubgroup argument ofbrm_data(),if applicable. Not every dataset has a subgroup variable.If yours does not, please either ignore this argument or set it toNULL.

time

Value of length 1, level of the discrete time columnin the data to label the prior. The discrete time columnis the one you identified with thetime argument ofbrm_data().

Value

Atibble with one row per model parameter and columns for theStan code, treatment group, subgroup, and discrete time pointof each parameter. You can supply thistibble to thelabelargument ofbrm_prior_archetype().

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other priors:brm_prior_archetype(),brm_prior_simple(),brm_prior_template()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 3,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )archetype <- brm_archetype_successive_cells(data)dplyr::distinct(data, group, time)label <- NULL |>  brm_prior_label("normal(1, 1)", group = "group_1", time = "time_1") |>  brm_prior_label("normal(1, 2)", group = "group_1", time = "time_2") |>  brm_prior_label("normal(1, 3)", group = "group_1", time = "time_3") |>  brm_prior_label("normal(2, 1)", group = "group_2", time = "time_1") |>  brm_prior_label("normal(2, 2)", group = "group_2", time = "time_2") |>  brm_prior_label("normal(2, 3)", group = "group_2", time = "time_3")label

Simple prior for abrms MMRM

Description

Generate a simple prior for abrms MMRM.

Usage

brm_prior_simple(  data,  formula,  intercept = "student_t(3, 0, 2.5)",  coefficients = "student_t(3, 0, 2.5)",  sigma = "student_t(3, 0, 2.5)",  unstructured = "lkj(1)",  autoregressive = "",  moving_average = "",  compound_symmetry = "",  correlation = NULL)

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

formula

An object of class"brmsformula" frombrm_formula()orbrms::brmsformula(). Should include the full mappingof the model, including fixed effects, residual correlation,and heterogeneity in the discrete-time-specific residual variancecomponents.

intercept

Character of length 1, Stan code for the priorto set on the intercept parameter.

coefficients

Character of length 1, Stan code for the priorto set independently on each of the non-intercept model coefficients.

sigma

Character of length 1, Stan code for the priorto set independently on each of the log-scale standard deviationparameters. Should be a symmetric prior in most situations.

unstructured

Character of length 1,Stan code for an unstructured correlation prior.Supply the empty string"" to set a flat prior (default).Applies to the⁠"cortime⁠ parameter class inbrms priors.Used for formulas created withbrm_formula(correlation = "unstructured"). LKJ is recommended.See alsobrms::unstr().

autoregressive

Character of length 1,Stan code for a prior on autoregressive correlation parameters.Supply the empty string"" to set a flat prior (default).Applies to the⁠"ar⁠ parameter class inbrms priors.Used for formulas created withbrm_formula(correlation = "autoregressive") andbrm_formula(correlation = "autoregressive_moving_average").See alsobrms::ar() andbrms::arma().

moving_average

Character of length 1,Stan code for a prior on moving average correlation parameters.Supply the empty string"" to set a flat prior (default).Applies to the⁠"ma⁠ parameter class inbrms priors.Used for formulas created withbrm_formula(correlation = "moving_average") andbrm_formula(correlation = "autoregressive_moving_average").See alsobrms::ma() andbrms::arma().

compound_symmetry

Character of length 1,Stan code for a prior on compound symmetry correlation parameters.Supply the empty string"" to set a flat prior (default).Applies to the⁠"cosy⁠ parameter class inbrms priors.Used for formulas created withbrm_formula(correlation = "compound_symmetry").See alsobrms::cosy().

correlation

Deprecated on 2024-04-22(version 0.1.0.9004). Please use arguments like"unstructured",and/or"autoregressive" to supply correlation-specific priors.

Details

Inbrm_prior_simple(), you can separately choose priors forthe intercept, model coefficients, log-scale standard deviations,and pairwise correlations between time points within patients.However, each class of parameters is set as a whole. In other words,brm_prior_simple() cannot assign different priorsto different fixed effect parameters.

Value

A classed data frame with thebrms prior.

See Also

Other priors:brm_prior_archetype(),brm_prior_label(),brm_prior_template()

Examples

set.seed(0L)data <- brm_simulate_outline()data <- brm_simulate_continuous(data, names = c("age", "biomarker"))formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE,  check_rank = FALSE)brm_prior_simple(  data = data,  formula = formula,  intercept = "student_t(3, 0, 2.5)",  coefficients = "normal(0, 10)",  sigma = "student_t(2, 0, 4)",  unstructured = "lkj(2.5)")

Label template for informative prior archetypes

Description

Template for thelabel argument ofbrm_prior_archetype().

Usage

brm_prior_template(archetype)

Arguments

archetype

An informative prior archetype generated by a functionlikebrm_archetype_successive_cells().

Details

Thelabel argument ofbrm_prior_archetype() is atibble which maps Stan code for univariate priorsto fixed effect parameters in the model. Usually thistibble isbuilt gradually using multiple calls tobrm_prior_label(),but occasionally it is more convenient to begin with a full templateand manually write Stan code in thecode column.brm_prior_template() creates this template.

Value

Atibble with one row per fixed effect parameter and columnsto map Stan code to each parameter. After manually writing Stan code inthecode column of the template, you can supply the resultto thelabel argument ofbrm_prior_archetype() to build abrms prior for your model.

Prior labeling

Informative prior archetypes use a labeling scheme to assign priorsto fixed effects. How it works:

1. First, assign the prior of each parameter a collection  of labels from the data. This can be done manually or with  successive calls to [brm_prior_label()].2. Supply the labeling scheme to [brm_prior_archetype()].  [brm_prior_archetype()] uses attributes of the archetype  to map labeled priors to their rightful parameters in the model.

For informative prior archetypes, this process is much more convenientand robust than manually callingbrms::set_prior().However, it requires an understanding of how the labels of the priorsmap to parameters in the model. This mapping varies from archetypeto archetype, and it is documented in the help pages ofarchetype-specific functions such asbrm_archetype_successive_cells().

See Also

Other priors:brm_prior_archetype(),brm_prior_label(),brm_prior_simple()

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 3,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )archetype <- brm_archetype_successive_cells(data)label <- brm_prior_template(archetype)label$code <- c(  "normal(1, 1)",  "normal(1, 2)",  "normal(1, 3)",  "normal(2, 1)",  "normal(2, 2)",  "normal(2, 3)")brm_prior_archetype(label = label, archetype = archetype)

Recenter nuisance variables

Description

Change the center of a nuisance variable of aninformative prior archetype.

Usage

brm_recenter_nuisance(data, nuisance, center)

Arguments

data

An informative prior archetype data frame output frombrm_archetype_cells() or similar.

nuisance

Character of length 1, name of the nuisance columnin the data to shift the center.

center

Numeric of length 1, value of the center to shiftthe column innuisance. The affected column in the returnedarchetype data frame will look as if it were centered by thisvalue to begin with.

Details

By "centering vector y at scalar x", we mean takingthe differencez = y - x. Ifx is the mean, thenmean(z) is0. Informative prior archetypes center nuisance variablesat their means so the parameters can be interpreted correctlyfor setting informative priors. This is appropriate most of the time,but sometimes it is better to center a column at a pre-specifiedscientifically meaningful fixed number. If you want a nuisance columnto be centered at a fixed value other than its mean,usebrm_recenter_nuisance() to shift the center. This functioncan handle any nuisance variable

Value

An informative prior archetype data frame with one of thevariables re-centered.

Examples

set.seed(0L)data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )archetype <- brm_archetype_cells(data)mean(archetype$nuisance_biomarker1) # after original centeringcenter <- mean(data$biomarker1)center # original center, before the centering from brm_archetype_cells()attr(archetype$nuisance_biomarker1, "brm_center") # original centermax(abs((data$biomarker1 - center) - archetype$nuisance_biomarker1))# Re-center nuisance_biomarker1 at 0.75.archetype <- brm_recenter_nuisance(  data = archetype,  nuisance = "nuisance_biomarker1",  center = 0.75)attr(archetype$nuisance_biomarker1, "brm_center") # new centermean(archetype$nuisance_biomarker1) # no longer equal to the center# nuisance_biomarker1 is now as though we centered it at 0.75.max(abs((data$biomarker1 - 0.75) - archetype$nuisance_biomarker1))

Deprecated: simulate an MMRM.

Description

Deprecated on 2023-09-01 (version 0.0.2.9001). Usebrm_simulate_simple() instead.

Usage

brm_simulate(  n_group = 2L,  n_patient = 100L,  n_time = 4L,  hyper_beta = 1,  hyper_sigma = 1,  hyper_correlation = 1)

Arguments

n_group

Positive integer of length 1, number of treatment groups.

n_patient

Positive integer of length 1, number of patientsper treatment group.

n_time

Positive integer of length 1, number of discretetime points (e.g. scheduled study visits) per patient.

hyper_beta

Positive numeric of length 1, hyperparameter.Prior standard deviation of the fixed effect parameters.

hyper_sigma

Positive numeric of length 1, hyperparameter.Uniform prior upper bound of the time-specific residualstandard deviation parameters.

hyper_correlation

Positive numeric of length 1, hyperparameter.LKJ shape parameter of the correlation matrix among repeatedmeasures within each patient.

Value

A list of three objects:

Examples

set.seed(0L)simulation <- suppressWarnings(brm_simulate())simulation$data

Append simulated categorical covariates

Description

Simulate and append non-time-varyingcategorical covariates to an existingbrm_data() dataset.

Usage

brm_simulate_categorical(data, names, levels, probabilities = NULL)

Arguments

data

Classedtibble as frombrm_data()orbrm_simulate_outline().

names

Character vector with the names of the new covariatesto simulate and append. Names must all be unique andmust not already be column names ofdata.

levels

Character vector of unique levels of thesimulated categorical covariates.

probabilities

EitherNULL or anumeric vector of lengthlength(levels) with levels between 0 and 1where all elements sum to 1.IfNULL, then all levels are equally likely to be drawn. If notNULL,thenprobabilities is a vector of sampling probabilities correspondingto each respective level oflevels.

Details

Each covariate is a new column of the dataset with one independentrandom categorical draw for each patient, using a fixed set of levels(viabase::sample() withreplace = TRUE).All covariates simulated this way areindependent of everything else in the data, including other covariates(to the extent that the random number generators in R work as intended).

Value

A classedtibble, like frombrm_data() orbrm_simulate_outline(), but with new categorical covariate columnsand with the names of the new covariates appended to thebrm_covariates attribute. Each new categorical covariate columnis a character vector, not the factor type in base R.

See Also

Other simulation:brm_simulate_continuous(),brm_simulate_outline(),brm_simulate_prior(),brm_simulate_simple()

Examples

data <- brm_simulate_outline()brm_simulate_categorical(  data = data,  names = c("site", "region"),  levels = c("area1", "area2"))brm_simulate_categorical(  data = data,  names = c("site", "region"),  levels = c("area1", "area2"),  probabilities = c(0.1, 0.9))

Append simulated continuous covariates

Description

Simulate and append non-time-varying continuouscovariates to an existingbrm_data() dataset.

Usage

brm_simulate_continuous(data, names, mean = 0, sd = 1)

Arguments

data

Classedtibble as frombrm_data()orbrm_simulate_outline().

names

Character vector with the names of the new covariatesto simulate and append. Names must all be unique andmust not already be column names ofdata.

mean

Numeric of length 1,mean of the normal distribution for simulating each covariate.

sd

Positive numeric of length 1,standard deviation of the normal distributionfor simulating each covariate.

Details

Each covariate is a new column of the dataset with one independentrandom univariate normal draw for each patient.All covariates simulated this way areindependent of everything else in the data, including other covariates(to the extent that the random number generators in R work as intended).

Value

A classedtibble, like frombrm_data() orbrm_simulate_outline(), but with new numeric covariate columnsand with the names of the new covariates appended to thebrm_covariates attribute.

See Also

Other simulation:brm_simulate_categorical(),brm_simulate_outline(),brm_simulate_prior(),brm_simulate_simple()

Examples

data <- brm_simulate_outline()brm_simulate_continuous(  data = data,  names = c("age", "biomarker"))brm_simulate_continuous(  data = data,  names = c("biomarker1", "biomarker2"),  mean = 1000,  sd = 100)

Start a simulated dataset

Description

Begin creating a simulated dataset.

Usage

brm_simulate_outline(  n_group = 2L,  n_subgroup = NULL,  n_patient = 100L,  n_time = 4L,  rate_dropout = 0.1,  rate_lapse = 0.05)

Arguments

n_group

Positive integer of length 1, number of treatment groups.

n_subgroup

Positive integer of length 1, number of subgroup levels.Set toNULL to omit the subgroup entirely.

n_patient

Positive integer of length 1.Ifn_subgroup isNULL, thenn_patient is the number of patientsper treatment group. Otherwise,n_patient is the number of patientsper treatment groupper subgroup. In both cases, the total number ofpatients in the whole simulated dataset is usually much greater than then_patients argument ofbrm_simulate_outline().

n_time

Positive integer of length 1, number of discretetime points (e.g. scheduled study visits) per patient.

rate_dropout

Numeric of length 1 between 0 and 1,post-baseline dropout rate.A dropout is an intercurrent event when datacollection for a patient stops permanently,causing the outcomes for that patient to be missing during and afterthe dropout occurred. The first time point is assumed to be baseline,so dropout is there. Dropouts are equally likely to occur at each ofthe post-baseline time points.

rate_lapse

Numeric of length 1, expected proportion of post-baselineoutcomes that are missing. Missing outcomes of this type are independentand uniformly distributed across the data.

Value

A classed data frame frombrm_data().The data frame has one row perpatient per time point and the following columns:

See Also

Other simulation:brm_simulate_categorical(),brm_simulate_continuous(),brm_simulate_prior(),brm_simulate_simple()

Examples

brm_simulate_outline()

Prior predictive draws.

Description

Simulate the outcome variable from the priorpredictive distribution of an MMRM usingbrms.

Usage

brm_simulate_prior(  data,  formula,  prior = brms.mmrm::brm_prior_simple(data = data, formula = formula),  ...)

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

formula

An object of class"brmsformula" frombrm_formula()orbrms::brmsformula(). Should include the full mappingof the model, including fixed effects, residual correlation,and heterogeneity in the discrete-time-specific residual variancecomponents.

prior

A validbrms prior object with proper priors for parametersb (model coefficients),b_sigma (log residual standard deviationsfor each time point), andcortime (residual correlations amongtime points within patients). See thebrm_prior_simple() function for an example.

...

Named arguments to specificbrm_formula() methods.

Details

brm_simulate_prior() callsbrms::brm() withsample_prior = "only", which sets the default intercept priorusing the outcome variable and requires at least some elements of theoutcome variable to be non-missing in advance. So to provide feasible andconsistent output,brm_simulate_prior() temporarily sets theoutcome variable to all zeros before invokingbrms::brm().

Value

A list with the following elements:

See Also

Other simulation:brm_simulate_categorical(),brm_simulate_continuous(),brm_simulate_outline(),brm_simulate_simple()

Examples

if (identical(Sys.getenv("BRM_EXAMPLES", unset = ""), "true")) {set.seed(0L)data <- brm_simulate_outline()data <- brm_simulate_continuous(data, names = c("age", "biomarker"))data$response <- rnorm(nrow(data))formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)tmp <- utils::capture.output(  suppressMessages(    suppressWarnings(      out <- brm_simulate_prior(        data = data,        formula = formula      )    )  ))out$data}

Simple MMRM simulation.

Description

Simple function to simulate a dataset from a simplespecialized MMRM.

Usage

brm_simulate_simple(  n_group = 2L,  n_patient = 100L,  n_time = 4L,  hyper_beta = 1,  hyper_tau = 0.1,  hyper_lambda = 1)

Arguments

n_group

Positive integer of length 1, number of treatment groups.

n_patient

Positive integer of length 1, number of patientsper treatment group.

n_time

Positive integer of length 1, number of discretetime points (e.g. scheduled study visits) per patient.

hyper_beta

Positive numeric of length 1, hyperparameter.Prior standard deviation of the fixed effect parametersbeta.

hyper_tau

Positive numeric of length 1, hyperparameter.Prior standard deviation parameter of the residual log standarddeviation parameterstau

hyper_lambda

Positive numeric of length 1, hyperparameter.Prior shape parameter of the LKJ correlation matrix of the residualsamong discrete time points.

Details

Refer to the methods vignette for a full model specification.Thebrm_simulate_simple() function simulates a dataset from asimple pre-defined MMRM. It assumes a cell means structure for fixedeffects, which means there is one fixed effect scalar parameter(element of vectorbeta) for each unique combination of levels oftreatment group and discrete time point.The elements ofbeta have independent univariate normalpriors with mean 0 and standard deviationhyper_beta.The residual log standard deviation parameters (elements of vectortau)have normal priors with mean 0 and standard deviationhyper_tau.The residual correlation matrix parameterlambda has an LKJ correlationprior with shape parameterhyper_lambda.

Value

A list of three objects:

See Also

Other simulation:brm_simulate_categorical(),brm_simulate_continuous(),brm_simulate_outline(),brm_simulate_prior()

Examples

set.seed(0L)simulation <- brm_simulate_simple()simulation$data

Marginal mean transformation

Description

Transformation from model parameters to marginal means.

Usage

brm_transform_marginal(  data,  formula,  average_within_subgroup = NULL,  prefix = "b_")

Arguments

data

A classed data frame frombrm_data(), or an informativeprior archetype from a function likebrm_archetype_successive_cells().

formula

An object of class"brmsformula" frombrm_formula()orbrms::brmsformula(). Should include the full mappingof the model, including fixed effects, residual correlation,and heterogeneity in the discrete-time-specific residual variancecomponents.

average_within_subgroup

TRUE to average concomitant covariatesproportionally within subgroup levels,FALSE to average thesecovariates across the whole dataset. Ifaverage_within_subgroup isNULL (default), and if the model has a subgroup and nuisance variables,thenbrm_transform_marginal() prints and informative message(once per session) and setsaverage_within_subgroup toFALSE.If you see this message, please readhttps://openpharma.github.io/brms.mmrm/articles/inference.html,decide whether to setaverage_within_subgroup toTRUE orFALSEinbrm_transform_marginal(), and then manually supply the output ofbrm_transform_marginal() to thetransform argument ofbrm_marginal_draws().

To create marginal means,brms.mmrm conditions the nuisance covariateson their averages across the whole dataset(average_within_subgroup = FALSE orNULLinbrm_transform_marginal()).This may be reasonable in some cases,and it mitigates the kind of hidden confounding between the subgroupand other variables which may otherwise cause Simpson's paradox.However, for subgroup-specific marginal means, it may not be realisticto condition on a single point estimate for all levels of the referencegrid(for example, if the subgroup is female vs male, but all marginalmeans condition on a single overall observed pregnancy rate of 5%).In these situations, it may be appropriate to instead condition onsubgroup-specific averages of nuisance variables(average_within_subgroup = TRUE inbrm_transform_marginal()).But if you do this,it is your responsibility to investigate and understand thehidden interactions and confounding in your dataset.For more information, please visithttps://openpharma.github.io/brms.mmrm/articles/inference.htmlandhttps://cran.r-project.org/package=emmeans/vignettes/interactions.html.

prefix

Character of length 1, prefix to add tothe model matrix ("X") frombrms::make_standata() in order toreconstruct thebrms model parameter names. This argument shouldonly be modified for testing purposes.

Details

The matrix frombrm_transform_marginal() is passed tothetransform_marginal argument ofbrm_marginal_draws(),and it transforms posterior draws of model parameters toposterior draws of marginal means. You may customize the output ofbrm_transform_marginal() before passing it tobrm_marginal_draws().However, please do not modify the dimensions, row names, or columnnames.

Value

A matrix to transform model parameters (columns) intomarginal means (rows).

Examples

set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)transform <- brm_transform_marginal(data = data, formula = formula)equations <- summary(transform)print(equations)summary(transform, message = FALSE)class(transform)print(transform)

Summarize an informative prior archetype.

Description

For an informative prior archetype, showthe transformation from model parameters to marginal means.

Usage

## S3 method for class 'brms_mmrm_archetype'summary(object, message = TRUE, ...)

Arguments

object

The informative prior archetype to summarize.

message

TRUE to print an informative message about the archetypeand invisibly return a character vector of equations.FALSEto forgo verbose messages and non-invisibly return the equations.

...

Not used, but required for S3 methods that inherit fromthe base genericsummary().

Value

Return a character vector with linear equationsthat map model parameters to marginal means. If themessageargument isTRUE (default) then this character vector is returnedinvisibly and a verbose description of the equations is printed.

Examples

data <- brm_simulate_outline(  n_group = 2,  n_patient = 100,  n_time = 4,  rate_dropout = 0,  rate_lapse = 0) |>  dplyr::mutate(response = rnorm(n = dplyr::n())) |>  brm_data_change() |>  brm_simulate_continuous(names = c("biomarker1", "biomarker2")) |>  brm_simulate_categorical(    names = c("status1", "status2"),    levels = c("present", "absent")  )dplyr::select(  data,  group,  time,  patient,  starts_with("biomarker"),  starts_with("status"))archetype <- brm_archetype_successive_cells(data)equations <- summary(archetype)print(equations)summary(archetype, message = FALSE)

Summarize marginal transform.

Description

Summarize a transformation from model parameters tomarginal means.

Usage

## S3 method for class 'brms_mmrm_transform_marginal'summary(object, message = TRUE, ...)

Arguments

object

Thebrm_transform_marginal() matrix to summarize.

message

TRUE to print an informative message about the archetypeand invisibly return a character vector of equations.FALSEto forgo verbose messages and non-invisibly return the equations.

...

Not used, but required for S3 methods that inherit fromthe base genericsummary().

Value

Return a character vector with linear equationsthat map model parameters to marginal means. If themessageargument isTRUE (default) then this character vector is returnedinvisibly and a verbose description of the equations is printed.

Examples

set.seed(0L)data <- brm_data(  data = brm_simulate_simple()$data,  outcome = "response",  group = "group",  time = "time",  patient = "patient",  reference_group = "group_1",  reference_time = "time_1")formula <- brm_formula(  data = data,  baseline = FALSE,  baseline_time = FALSE)transform <- brm_transform_marginal(data = data, formula = formula)equations <- summary(transform)print(equations)summary(transform, message = FALSE)class(transform)print(transform)

[8]ページ先頭

©2009-2025 Movatter.jp