| 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 Landau |
| 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
Bürkner, P.-C. (2017), "brms: An R package for Bayesianmultilevel models using Stan,"Journal of Statistical Software, 80, 1–28.https://doi.org/10.18637/jss.v080.i01.
Holzhauer, B., and Weber, S. (2024),"Bayesian mixed effects model for repeated measures,"in Applied Modeling in Drug Development, Novartis AG.https://opensource.nibr.com/bamdd/src/02h_mmrm.html.
Mallinckrodt, C. H., Lane, P. W., Schnell, D., and others (2008),"Recommendations for the primary analysis of continuous endpointsin longitudinal clinical trials,"Therapeutic Innovation and Regulatory Science, 42, 303–319.https://doi.org/10.1177/009286150804200402.
Mallinckrodt, C. H., and Lipkovich, I. (2017),Analyzing longitudinal clinical trial data: A practical guide,CRC Press, Taylor & Francis Group.
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 from |
intercept | Logical of length 1. |
baseline | Logical of length 1. |
baseline_subgroup | Logical of length 1. |
baseline_subgroup_time | Logical of length 1. |
baseline_time | Logical of length 1. |
covariates | Logical of length 1. |
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_nuisance | Same as |
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 thebeta_* 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 from |
intercept | Logical of length 1. |
baseline | Logical of length 1. |
baseline_subgroup | Logical of length 1. |
baseline_subgroup_time | Logical of length 1. |
baseline_time | Logical of length 1. |
covariates | Logical of length 1. |
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_nuisance | Same as |
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 thebeta_* 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 from |
intercept |
|
baseline | Logical of length 1. |
baseline_subgroup | Logical of length 1. |
baseline_subgroup_time | Logical of length 1. |
baseline_time | Logical of length 1. |
covariates | Logical of length 1. |
clda |
Some archetypes cannot support cLDA(e.g. In cLDA, the fixed effects parameterizationis restricted such that all treatment groups are pooled at baseline.(If you supplied a |
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_nuisance | Same as |
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 from |
intercept |
|
baseline | Logical of length 1. |
baseline_subgroup | Logical of length 1. |
baseline_subgroup_time | Logical of length 1. |
baseline_time | Logical of length 1. |
covariates | Logical of length 1. |
clda |
Some archetypes cannot support cLDA(e.g. In cLDA, the fixed effects parameterizationis restricted such that all treatment groups are pooled at baseline.(If you supplied a |
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_nuisance | Same as |
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 from |
intercept |
|
baseline | Logical of length 1. |
baseline_subgroup | Logical of length 1. |
baseline_subgroup_time | Logical of length 1. |
baseline_time | Logical of length 1. |
covariates | Logical of length 1. |
clda |
Some archetypes cannot support cLDA(e.g. In cLDA, the fixed effects parameterizationis restricted such that all treatment groups are pooled at baseline.(If you supplied a |
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_nuisance | Same as |
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 from |
intercept | Logical of length 1. |
baseline | Logical of length 1. |
baseline_subgroup | Logical of length 1. |
baseline_subgroup_time | Logical of length 1. |
baseline_time | Logical of length 1. |
covariates | Logical of length 1. |
clda |
Some archetypes cannot support cLDA(e.g. In cLDA, the fixed effects parameterizationis restricted such that all treatment groups are pooled at baseline.(If you supplied a |
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_nuisance | Same as |
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 |
baseline | Character of length 1,name of the baseline response variable (for example, |
group | Character of length 1, name of the treatment group variable.Example possibilities from clinical trial datasets include |
subgroup | Character of length 1, optional name of the adiscrete subgroup variable. Set to |
time | Character of length 1, name of the discrete time variable.Example possibilities from clinical trial datasets include Ordinarily, ordered factors automatically use polynomial contrasts from |
patient | Character of length 1, name of the patient ID variable.Example possibilities from clinical trial datasets include |
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 call |
missing | Character of length 1, name of an optional variablein a simulated dataset to indicate which outcome values should be missing.Set to |
reference_group | Atomic value of length 1, Level of the |
reference_subgroup | Atomic value of length 1,level of the |
reference_time | Atomic value of length 1 or If Note: |
role | Deprecated as unnecessary on 2024-07-11 (version 1.0.1.9007).Use |
level_baseline | Deprecated on 2024-01-11 (version 0.2.0.9002).Use |
level_control | Deprecated on 2024-01-11 (version 0.2.0.9002).Use |
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:
Perform basic assertions to make sure the data and other argumentsare properly formatted.
Convert the group and time columns to character vectors.
Sanitize the levels of the group and time columns using
make.names(unique = FALSE, allow_ = TRUE)to ensure agreementbetween the data and the output ofbrms.For each implicitly missing outcome observation, add explicit rowwith the outcome variable equal to
NA_real_. Missing valuesin the predictors are implicitly filled usingzoo::na.locf()on within each patient, which is not valid for time-varyingcovariates. If any covariates are time-varying, pleasemanually perform this step before callingbrm_data().Arrange the rows of the data by group, then patient, then discrete time.
Select only the columns of the data relevant to an MMRM analysis.
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 classed |
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.Either |
levels | Optional character vector of levels of |
time | Character string with the name of the discrete timevariable in the data. This is the variable that |
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 orderModel 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 from |
model_missing_outcomes | Logical of length 1, |
check_rank |
|
sigma | A formula produced by |
correlation | Character of length 1, name of the correlationstructure. The correlation matrix is a square
|
autoregressive_order | Nonnegative integer,autoregressive order for the |
moving_average_order | Nonnegative integer,moving average order for the |
residual_covariance_arma_estimation |
|
... | Named arguments to specific |
intercept | Logical of length 1. |
baseline | Logical of length 1. |
baseline_subgroup | Logical of length 1. |
baseline_subgroup_time | Logical of length 1. |
baseline_time | Logical of length 1. |
covariates | Logical of length 1. |
group | Logical of length 1. |
group_subgroup | Logical of length 1. |
group_subgroup_time | Logical of length 1. |
group_time | Logical of length 1. |
subgroup | Logical of length 1. |
subgroup_time | Logical of length 1. |
time | Logical of length 1. |
center |
|
effect_baseline | Deprecated on 2024-01-16 (version 0.0.2.9002).Use |
effect_group | Deprecated on 2024-01-16 (version 0.0.2.9002).Use |
effect_time | Deprecated on 2024-01-16 (version 0.0.2.9002).Use |
interaction_baseline | Deprecated on 2024-01-16 (version 0.0.2.9002).Use |
interaction_group | Deprecated on 2024-01-16 (version 0.0.2.9002).Use |
warn_ignored | Set to |
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:
Any interactions with the concomitant covariates you specified in the
covariatesargument ofbrm_data().Any interactions which include baseline response and treatmentgroup together. Rationale: in a randomized controlled experiment,baseline and treatment group assignment should be uncorrelated.
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() usesthex_* andnuisance_* 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)formulaFormula 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 from |
check_rank |
|
intercept | Logical of length 1. |
baseline | Logical of length 1. |
baseline_subgroup | Logical of length 1. |
baseline_subgroup_time | Logical of length 1. |
baseline_time | Logical of length 1. |
covariates | Logical of length 1. |
group | Logical of length 1. |
group_subgroup | Logical of length 1. |
group_subgroup_time | Logical of length 1. |
group_time | Logical of length 1. |
subgroup | Logical of length 1. |
subgroup_time | Logical of length 1. |
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 from |
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:
group: treatment group.subgroup: subgroup level. Only included if thesubgroupargument ofbrm_marginal_data()isTRUE.time: discrete time point.statistic: type of summary statistic.value: numeric value of the estimate.
Thestatistic column has the following possible values:
mean: observed mean response after removing missing values.median: observed median response after removing missing values.sd: observed standard deviation of the response afterremoving missing values.lower: lower bound of a normal equal-tailed confidence intervalwith confidence level determined by thelevelargument.upper: upper bound of a normal equal-tailed confidence intervalwith confidence level determined by thelevelargument.n_observe: number of non-missing values in the response.n_total: number of total records in the data for the givengroup/time combination, including both observed and missing 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 from |
data | A classed data frame from |
formula | An object of class |
transform | Matrix with one row per marginal mean and one columnper model parameter. |
effect_size | Logical, |
average_within_subgroup |
|
use_subgroup | Deprecated. No longer used. |
control | Deprecated. Set the control group level in |
baseline | Deprecated. Set the control group level in |
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:
response: on the scale of the response variable.difference_time: change from baseline: theresponseat a particular time minus theresponseat baseline(reference_time).Only returned if thereference_timeargument ofbrm_data()wasnotNULL(i.e. if a baseline value for the time variablewas identified).difference_group: treatment effect:These samples depend on the values ofreference_groupandreference_timewhich were originally declared inbrm_data().reference_groupis the control group, andreference_timeis baseline. If baseline was originally given (viareference_timeinbrm_data()),thendifference_timeis the change-from-baseline value ofeach active group minus that of the control group.Otherwise, if baseline is omitted (i.e.reference_time = NULL(default) inbrm_data()), thendifference_timeis theraw response at each active group minus that of the control group.difference_subgroup: subgroup differences: thedifference_groupat each subgroup level minus thedifference_groupat the subgroupreference level (reference_subgroup). Only reported if a subgroupanalysis was specified through the appropriate arguments tobrm_data()andbrm_formula().effect: effect size, defined as the treatment differencedivided by the residual standard deviation. Omitted iftheeffect_sizeargument isFALSEor if thebrm_formula_sigma()includes baseline or covariates.sigma: posterior draws of linear-scale marginal standard deviationsof residuals. Omitted iftheeffect_sizeargument isFALSEor if thebrm_formula_sigma()includes baseline or covariates.
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 from |
data | A classed data frame from |
times | Character vector of discrete time point levelsover which to average the MCMC samples within treatment group levels.Set to |
label | Character of length 1, time point label for the averages.Automatically sanitized with |
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 from |
formula | An object of class |
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 from |
direction | Character vector of the same length as |
threshold | Numeric vector of the same length as |
Value
A tibble of probabilities of the formProb(treatment effect > threshold | data) and/orProb(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 from |
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:
marginal: type of marginal distribution. Ifoutcomewas"response"inbrm_marginal_draws(), then possible values include"response"for the response on the raw scale,"change"forchange from baseline, and"difference"for treatment differencein terms of change from baseline. Ifoutcomewas"change",then possible values include"response"for the response one thechange from baseline scale and"difference"for treatment difference.statistic: type of summary statistic."lower"and"upper"are bounds of an equal-tailed quantile-based credible interval.group: treatment group.subgroup: subgroup level, if applicable.time: discrete time point.value: numeric value of the estimate.mcse: Monte Carlo standard error of the estimate.Thestatisticcolumn has the following possible values:mean: posterior mean.median: posterior median.sd: posterior standard deviation of the mean.lower: lower bound of an equal-tailed credible interval of the mean,with credible level determined by thelevelargument.upper: upper bound of an equal-tailed credible intervalwith credible level determined by thelevelargument.
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 from If you supply a non- |
formula | An object of class |
... | Arguments to |
prior | Either |
family | A |
imputed | Either If not Even if you supply |
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
... | Named |
marginal | Character of length 1, which kind of marginalto visualize. Must be a value in the |
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 |
axis | Character of length 1 identifying the quantity to puton the horizontal axis. Must be be one of |
facet | Character vector of length 1 or 2 with quantities togenerate facets. Each element must be |
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 of |
axis | Character of length 1 identifying the quantity to puton the horizontal axis. Must be be one of |
facet | Character vector of length 1 or 2 with quantities togenerate facets. Each element must be |
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 using |
archetype | An informative prior archetype generated by a functionlike |
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 | A |
code | Character of length 1, Stan code for the prior. Could bea string like |
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 the |
subgroup | Value of length 1, level of the subgroup columnin the data to label the prior. The subgroup columnis the one you identified with the |
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 the |
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")labelSimple 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 from |
formula | An object of class |
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 |
autoregressive | Character of length 1,Stan code for a prior on autoregressive correlation parameters.Supply the empty string |
moving_average | Character of length 1,Stan code for a prior on moving average correlation parameters.Supply the empty string |
compound_symmetry | Character of length 1,Stan code for a prior on compound symmetry correlation parameters.Supply the empty string |
correlation | Deprecated on 2024-04-22(version 0.1.0.9004). Please use arguments like |
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 functionlike |
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 from |
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 in |
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:
data: A tidy dataset with one row per patient per discretetime point and columns for the response and covariates.model_matrix: A matrix with one row per row ofdataand columnsthat represent levels of the covariates.parameters: A named list of parameter values sampled from the prior.
Examples
set.seed(0L)simulation <- suppressWarnings(brm_simulate())simulation$dataAppend 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 | Classed |
names | Character vector with the names of the new covariatesto simulate and append. Names must all be unique andmust not already be column names of |
levels | Character vector of unique levels of thesimulated categorical covariates. |
probabilities | Either |
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 | Classed |
names | Character vector with the names of the new covariatesto simulate and append. Names must all be unique andmust not already be column names of |
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 to |
n_patient | Positive integer of length 1.If |
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:
group: integer index of the treatment group.patient: integer index of the patient.time: integer index of the discrete time point.
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 from |
formula | An object of class |
prior | A valid |
... | Named arguments to specific |
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:
data: a classedtibblewith the outcome variable simulated as a drawfrom the prior predictive distribution (the final row ofoutcomeinthe output). If you simulated a missingness patternwithbrm_simulate_outline(), then that missingness pattern is appliedso that the appropriate values of the outcome variable are set toNA.model: thebrmsmodel fit object.model_matrix: the model matrix of the fixed effects, obtained frombrms::make_standata().outcome: a numeric matrix with one column per row ofdataand onerow per saved prior predictive draw.parameters: atibbleof saved parameter draws from the priorpredictive distribution.
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 parameters |
hyper_tau | Positive numeric of length 1, hyperparameter.Prior standard deviation parameter of the residual log standarddeviation parameters |
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:
data: A tidy dataset with one row per patient per discretetime point and columns for the outcome and ID variables.model_matrix: A matrix with one row per row ofdataand columnsthat represent levels of the covariates.parameters: A named list of parameter draws sampled from the prior:beta: numeric vector of fixed effects.tau: numeric vector of residual log standard parameters for eachtime point.sigma: numeric vector of residual standard parameters for eachtime point.sigmais equal toexp(tau).lambda: correlation matrix of the residuals among the time pointswithin each patient.covariance: covariance matrix of the residuals among the time pointswithin each patient.covarianceis equal todiag(sigma) %*% lambda %*% diag(sigma).
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$dataMarginal 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 from |
formula | An object of class |
average_within_subgroup |
To create marginal means, |
prefix | Character of length 1, prefix to add tothe model matrix ( |
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. |
... | Not used, but required for S3 methods that inherit fromthe base generic |
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 | The |
message | TRUE to print an informative message about the archetypeand invisibly return a character vector of equations. |
... | Not used, but required for S3 methods that inherit fromthe base generic |
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)