| Title: | Tools for Creating Publication-Ready Regression Tables |
|---|---|
| Description: | Simplifies regression modeling in R by integrating multiple modeling and summarization tools into a cohesive, user-friendly interface. Designed to be accessible for researchers, particularly those in Low- and Middle-Income Countries (LMIC). Built upon widely accepted statistical methods, including logistic regression (Hosmer et al. 2013, ISBN:9781118548429), log-binomial regression (Spiegelman and Hertzmark 2005 <doi:10.1093/aje/kwi188>), Firth penalized logistic regression (Firth 1993 <doi:10.1093/biomet/80.1.27>), Poisson and robust Poisson regression (Zou 2004 <doi:10.1093/aje/kwh090>), negative binomial regression (Hilbe 2011, ISBN:9780521179515), Cox proportional hazards regression, parametric survival regression, causal mediation analysis, and linear regression (Kutner et al. 2005, ISBN:9780071122214). Leverages multiple dependencies to ensure high-quality output and generate reproducible, publication-ready tables in alignment with best practices in epidemiology and applied statistics. |
| Authors: | Rubeshkumar Polani [aut, cre] (ORCID: <https://orcid.org/0000-0002-0418-7592>), Salin K Eliyas [aut] (ORCID: <https://orcid.org/0000-0002-8020-5860>), Manikandanesan Sakthivel [aut] (ORCID: <https://orcid.org/0000-0002-5438-3970>), Mogan Kaviprawin [aut] (ORCID: <https://orcid.org/0000-0002-1659-059X>), Yuvaraj Krishnamoorthy [aut] (ORCID: <https://orcid.org/0000-0003-4688-510X>), Marie Gilbert Majella [aut] (ORCID: <https://orcid.org/0000-0003-4036-5162>) |
| Maintainer: | Rubeshkumar Polani <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.1.0 |
| Built: | 2026-10-13 11:33:25 UTC |
| Source: | https://github.com/thinkdenominator/gtregression |
Works for any object from this package, since they all carry class '"gtregression"'. Returns NULL (quietly) if the field is not present.
## S3 method for class 'gtregression' x$name## S3 method for class 'gtregression' x$name
x |
A |
name |
Field name to access. |
Common fields: - table, table_display, table_body - models, model_summaries, reg_check - approach, format (or engine), source - parts, spanners (for merged tables) - by, levels (for descriptive tables)
Computes Variance Inflation Factors (VIF) for fitted multivariable models
returned by multi_reg() or related functions.
check_collinearity(model, format = c("flextable", "gt", "tibble"))check_collinearity(model, format = c("flextable", "gt", "tibble"))
model |
A fitted model object returned by |
format |
Output format. One of |
If the car package is installed, check_collinearity()
uses car::vif(). Otherwise, it computes VIF/GVIF from the fitted model
matrix so that diagnostics remain available without an additional dependency.
For multivariable models, a tibble if a single fitted model is
present, or a named list of tibbles if multiple fitted models are present.
With format = "gt" or format = "flextable", leaf tibbles are
converted to formatted tables while preserving any list nesting. The tibble
contains:
VariableModel term.
VIFVariance inflation factor. For multi-degree-of-freedom
terms, this is the adjusted GVIF: GVIF^(1 / (2 * Df)).
InterpretationSimple interpretation based on common cut points: no collinearity, moderate, or high.
For univariate models, an error is raised indicating that VIF is not applicable.
Check whether requested models converge, either one exposure at a time or as a single multivariable model.
check_convergence( data, exposures, outcome, approach = "logit", multivariate = FALSE, format = c("flextable", "gt", "tibble") )check_convergence( data, exposures, outcome, approach = "logit", multivariate = FALSE, format = c("flextable", "gt", "tibble") )
data |
A data frame containing the dataset. |
exposures |
A character vector of predictor variable names. Quoted names
are recommended in scripts, and bare names are also accepted.
If |
outcome |
A character string specifying the outcome variable. Quoted and bare names are accepted. |
approach |
A character string specifying the regression approach.
One of:
|
multivariate |
Logical. If |
format |
Output format. One of |
For robpoisson, predicted probabilities (fitted values) may exceed 1,
which is acceptable when estimating risk ratios but should not be interpreted
as actual probabilities.
This is especially useful for "logbinomial" models, where convergence
problems are common and robust Poisson may be a practical alternative.
A data frame, gt_tbl, or flextable summarizing
convergence diagnostics, including:
ExposureName of the exposure variable.
ModelThe regression approach used.
ConvergedTRUE if the model converged successfully;
FALSE otherwise.
Max.prob.Maximum predicted probability or fitted value in the dataset.
[identify_confounder()], [interaction_models()]
if (requireNamespace("gtregression", quietly = TRUE)) { data(data_SynthDiabetes, package = "gtregression") check_convergence( data = data_SynthDiabetes, exposures = c("age", "mass"), outcome = "diabetes", approach = "logit", format = "tibble" ) check_convergence( data = data_SynthDiabetes, exposures = c("age", "mass"), outcome = "diabetes", approach = "logit", multivariate = TRUE, format = "gt" ) }if (requireNamespace("gtregression", quietly = TRUE)) { data(data_SynthDiabetes, package = "gtregression") check_convergence( data = data_SynthDiabetes, exposures = c("age", "mass"), outcome = "diabetes", approach = "logit", format = "tibble" ) check_convergence( data = data_SynthDiabetes, exposures = c("age", "mass"), outcome = "diabetes", approach = "logit", multivariate = TRUE, format = "gt" ) }
Test the proportional hazards assumption for fitted Cox proportional hazards models using Schoenfeld residuals.
check_ph( model, transform = c("km", "rank", "identity"), alpha = 0.05, format = c("flextable", "gt", "tibble") )check_ph( model, transform = c("km", "rank", "identity"), alpha = 0.05, format = c("flextable", "gt", "tibble") )
model |
A fitted |
transform |
Time transformation passed to |
alpha |
Significance level used for the simple interpretation column. |
format |
Output format. One of |
check_ph() is a diagnostic aid for Cox models. A small p-value
suggests possible evidence against the proportional hazards assumption for a
term or for the global model test. This should be interpreted with plots,
clinical knowledge, follow-up patterns, and modelling purpose.
A tibble, gt_tbl, or flextable with Schoenfeld
residual proportional hazards tests. The table contains:
ModelModel name. For a direct coxph object, this is
"cox_model".
TermModel term or "GLOBAL".
Chi.squareChi-square statistic.
dfDegrees of freedom.
p.valueTest p-value.
InterpretationSimple screening interpretation using
alpha.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) cox_fit <- cox_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, age) ) check_ph(cox_fit) check_ph(cox_fit, format = tibble)lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) cox_fit <- cox_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, age) ) check_ph(cox_fit) check_ph(cox_fit, format = tibble)
Compare gtregression candidate models side by side using model-fit statistics.
This is intended for transparent model comparison after you have already
fitted the candidate models with functions such as multi_reg(),
cox_reg(), or surv_reg().
compare_models( ..., model_names = NULL, nested = TRUE, primary_exposure = NULL, exponentiate = NULL, digits = 2, p_digits = 3, format = c("flextable", "gt", "tibble"), theme = c("minimal") )compare_models( ..., model_names = NULL, nested = TRUE, primary_exposure = NULL, exponentiate = NULL, digits = 2, p_digits = 3, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
... |
Two or more gtregression model objects, or one list containing
them. Inputs should be outputs from |
model_names |
Optional character vector of names to display. If omitted,
names supplied in |
nested |
Logical. If |
primary_exposure |
Optional exposure or exact coefficient name to track across models. For Cox models this can be used to show the hazard ratio and percentage change in the log-effect estimate across candidate models. |
exponentiate |
Logical. If |
digits |
Number of digits for model statistics and estimates. |
p_digits |
Number of digits for p-values. |
format |
Output format. Defaults to |
theme |
Table theme preset. |
compare_models() does not refit models and does not perform hidden
complete-case filtering. It compares models already fitted by gtregression
and extracts the single fitted model stored in each object's models
element. The reported N, event counts, and fit statistics therefore come from
the model already fitted by multi_reg(), cox_reg(), or
surv_reg(). This keeps model comparison separate from model
selection: compare candidate models first, then choose the final model using
clinical, epidemiological, and statistical judgement.
The guided builder in gtregression_app() can create the fitted
gtregression objects before calling this function; the generated app code
exposes every model formula and comparison call.
Likelihood-ratio p-values are meaningful only for nested models fitted to
the same analysis sample. compare_models() checks whether the fitted
models appear to use the same analysis sample using retained model row
identifiers when available; otherwise it compares N and event counts. It
also checks whether sequential model pairs appear to be nested when
nested = TRUE. Rendered warnings are context-aware: no warning about
different analysis samples is shown when the compared models use the same
observations, and no nested-model warning is shown when sequential models
appear nested. AIC, BIC, log-likelihood, and likelihood-ratio statistics
remain visible when warnings are needed, but should then be interpreted with
the displayed caution.
A gtregression object with:
table: publication-ready table
table_body: raw comparison statistics
table_display: formatted display data
models: fitted models compared
comparison_status: whether models appear to use the same
analysis sample
comparison_warnings: caution messages that are highlighted
in rendered tables when interpretation needs extra care
gtregression_app(), multi_reg(), cox_reg(),
surv_reg(), select_models()
data("data_lungcancer", package = "gtregression") lung_data <- data_lungcancer cox_1 <- cox_reg( data = lung_data, time = time, event = status, exposures = trt ) cox_2 <- cox_reg( data = lung_data, time = time, event = status, exposures = trt, adjust_for = c(age, karno) ) compare_models( cox_1, cox_2, primary_exposure = trt ) compare_models( cox_1, cox_2, model_names = c("Treatment only", "Treatment + age + performance"), primary_exposure = trt )data("data_lungcancer", package = "gtregression") lung_data <- data_lungcancer cox_1 <- cox_reg( data = lung_data, time = time, event = status, exposures = trt ) cox_2 <- cox_reg( data = lung_data, time = time, event = status, exposures = trt, adjust_for = c(age, karno) ) compare_models( cox_1, cox_2, primary_exposure = trt ) compare_models( cox_1, cox_2, model_names = c("Treatment only", "Treatment + age + performance"), primary_exposure = trt )
Fit Cox proportional hazards models and report hazard ratios.
cox_reg( data, time, event, exposures, adjust_for = NULL, stratifier = NULL, interaction = NULL, multivariable = FALSE, multivariate = NULL, format = c("flextable", "gt"), theme = c("minimal"), show_sample = "events", model_stats = FALSE, show_ref = TRUE )cox_reg( data, time, event, exposures, adjust_for = NULL, stratifier = NULL, interaction = NULL, multivariable = FALSE, multivariate = NULL, format = c("flextable", "gt"), theme = c("minimal"), show_sample = "events", model_stats = FALSE, show_ref = TRUE )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
exposures |
Character vector of exposure variable names. Quoted names are recommended in scripts, and bare names are also accepted. |
adjust_for |
Optional character vector of adjustment variables. When supplied, one adjusted Cox model is fitted per exposure. |
stratifier |
Optional single stratifying variable. When supplied, stratum-specific Cox tables are produced using the same crude, adjusted, or multivariable workflow requested by the other arguments. The stratifier cannot also be used as the time, event, exposure, adjustment, or interaction variable. |
interaction |
Optional character scalar specifying one interaction term
using standard formula syntax, e.g. |
multivariable |
Logical; if |
multivariate |
Optional logical alias for |
format |
Output table format; one of |
theme |
Table styling preset. |
show_sample |
For stratified Cox tables, controls which sample-size
columns are shown in the publication table. One of |
model_stats |
Logical; if |
show_ref |
Logical; if |
By default, cox_reg() keeps the exposure-by-exposure workflow:
without adjust_for, one crude Cox model is fitted per exposure; with
adjust_for, one adjusted Cox model is fitted per exposure and only the
exposure estimate is reported. This is useful for screening or for reporting
several adjusted exposure effects.
With multivariable = TRUE, all variables in exposures are
included in a single Cox model and all coefficients are reported. This mirrors
the multivariable workflow used by multi_reg(). The
adjust_for argument is not used in this mode; include every variable
that belongs in the model inside exposures. Since these estimates are
adjusted for the other variables in the same model, the table reports
Adjusted HR (95% CI).
Interaction terms specified via interaction are included using
standard formula expansion (for example, trt*prior). Interaction
effects are displayed as additional rows beneath the corresponding exposure.
The proportional hazards assumption should be assessed separately, for
example with check_ph().
Stratified Cox tables show event counts by default. Use
show_sample = "n", show_sample = "both", or
show_sample = "none" to control the displayed sample columns. Crude
stratified tables calculate these counts for each exposure-specific model;
adjusted and multivariable stratified tables use the corresponding fitted
model within each stratum.
If exposure variables have a "label" attribute, for example from
labelled::var_label(), those labels are used automatically in the
displayed table.
A list of class c("gtregression","cox_reg", ...) with elements:
A flextable or gt_tbl.
Data frame of hazard ratios and confidence intervals.
Data frame used to render the publication table.
List of fitted coxph models.
Summary output for the fitted models.
Model-fit statistics when model_stats = TRUE;
otherwise NULL.
Named character vector of display labels.
Character vector used by the rendered table. Adjustment notes use the same display labels as the table.
Metadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) lung_data$prior <- factor(lung_data$prior, levels = c(0, 10), labels = c("No", "Yes")) cox_reg( data = lung_data, time = time, event = status, exposures = c("trt", "celltype", "karno", "age") ) cox_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, prior), adjust_for = c(age, karno) ) # Interaction in an adjusted exposure model cox_reg( data = lung_data, time = time, event = status, exposures = trt, adjust_for = c(age, karno), interaction = trt*prior ) cox_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, prior, age, karno), multivariable = TRUE ) # multivariate is accepted as an alias cox_reg( data = lung_data, time = time, event = status, exposures = c(trt, age, karno), multivariate = TRUE )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) lung_data$prior <- factor(lung_data$prior, levels = c(0, 10), labels = c("No", "Yes")) cox_reg( data = lung_data, time = time, event = status, exposures = c("trt", "celltype", "karno", "age") ) cox_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, prior), adjust_for = c(age, karno) ) # Interaction in an adjusted exposure model cox_reg( data = lung_data, time = time, event = status, exposures = trt, adjust_for = c(age, karno), interaction = trt*prior ) cox_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, prior, age, karno), multivariable = TRUE ) # multivariate is accepted as an alias cox_reg( data = lung_data, time = time, event = status, exposures = c(trt, age, karno), multivariate = TRUE )
A dataset from the MASS package containing risk factors associated with low birth weight (LBW) in newborns. Originally collected at Baystate Medical Center, Springfield, Massachusetts, USA.
data_birthwtdata_birthwt
A data frame with 189 observations and 10 variables:
Indicator for birth weight < 2500g (binary):
0 = normal, 1 = low birth weight
Mother's age in years (numeric)
Mother's weight in pounds at last menstrual period (numeric)
Mother's race (factor): 1 = White, 2 = Black,
3 = Other
Smoking status during pregnancy (binary): 0 = No,
1 = Yes
Number of previous premature labors (integer)
History of hypertension (binary): 0 = No, 1 = Yes
Presence of uterine irritability (binary): 0 = No,
1 = Yes
no of physician visits during the 1st trimester (integer, 0–6)
Birth weight in grams (numeric)
The outcome variable is binary ('low'): birth weight < 2500g (yes = 1) or not (no = 0).
Hosmer, D.W., Lemeshow, S. (1989). *Applied Logistic Regression.* New York: Wiley. Also available in MASS and described in detail in its documentation.
A health-related teaching dataset prepared from synthetic diabetes data. It is designed for the practical question: could part of the obesity and diabetes relationship operate through plasma glucose, after adjustment for basic clinical covariates?
data_diabetes_mediationdata_diabetes_mediation
A data frame with variables:
Diabetes status (No, Yes)
Obesity status based on BMI >= 30 (No, Yes)
Plasma glucose concentration
Body mass index
Age in years
Diastolic blood pressure
Number of pregnancies
Diabetes pedigree function
This dataset is intended for practice and teaching. Mediation estimates from observational data should be interpreted causally only when the temporal ordering and no-unmeasured-confounding assumptions are justified by study design, DAGs, and subject-matter knowledge.
Derived from data_SynthDiabetes, which is based on
mlbench::SynthDiabetes2 (mlbench version 2.1-11 or later).
A classic endometrial cancer dataset used to demonstrate separation in logistic regression. The outcome is high histology grade. Neovascularization is completely absent among low-grade cases in this dataset, making it useful for teaching Firth penalized logistic regression.
data_endometrialdata_endometrial
A data frame with 79 observations and 4 variables:
Neovascularization status (0 = absent, 1 = present)
Pulsatility index of the uterine artery
Endometrium height
Histology grade (0 = low grade, 1 = high grade)
brglm2 package. The packaged dataset was sourced from https://users.stat.ufl.edu/~aa/glm/data/, the data repository used in Agresti (2015). Originally analyzed in Heinze and Schemper (2002).
Agresti A (2015). Foundations of Linear and Generalized Linear Models. Wiley.
Heinze G, Schemper M (2002). A solution to the problem of separation in logistic regression. Statistics in Medicine, 21, 2409-2419. doi:10.1002/sim.1047
RCT on the effect of a drug on the seizures in patients with epilepsy. Contains repeated measures data with treatment groups, baseline seizure counts, and follow-up counts.
data_epilepsydata_epilepsy
A data frame with 236 observations and 9 variables:
Number of seizures in a 2-week period (count)
Treatment group (factor): placebo or progabide
Seizure count during baseline period (numeric)
Age of patient (numeric)
Indicator for 4th visit (binary)
Patient ID (factor)
Follow-up period number (integer)
Log of baseline seizures (numeric)
Log of age (numeric)
MASS package. Original data from Thall and Vail (1990)
This dataset contains observations on the number of days absent from school for children in rural Australia, along with student characteristics. It's commonly used to demonstrate count models such as Poisson and Negative Binomial regression.
data_gt_quindata_gt_quin
A data frame with 146 observations and 5 variables:
Ethnicity ("A" = Aboriginal,
"N" = Non-Aboriginal)
Sex ("F" or "M")
Age group ("F0", "F1", "F2", "F3")
Learner status ("AL" = average learner,
"SL" = slow learner)
Number of days absent from school (count outcome)
MASS package. See also Venables and Ripley (2002), *Modern Applied Statistics with S*.
investigating the relationship between infertility and abortions.
data_infertilitydata_infertility
A data frame with 248 observations and 8 variables:
Education level (0 = 0–5 years, 1 = 6–11 years, 2 = 12+ years)
Age in years
Number of prior pregnancies
Number of induced abortions
Infertility case status (1 = case, 0 = control)
Number of spontaneous abortions
Matched set ID
Pooled stratum ID used for conditional regression
https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/infert.html
Survival data from a clinical trial of lung cancer patients conducted by the Veteran's Administration.
data_lungcancerdata_lungcancer
A data frame with 137 observations and 8 variables:
Treatment group (1 = standard, 2 = test)
Cell type (squamous, smallcell, adeno, large)
Survival time (in days)
Censoring status (1 = died, 0 = censored)
Karnofsky performance score (higher = better)
Months from diagnosis to randomization
Age in years
Prior therapy (0 = no, 10 = yes)
https://CRAN.R-project.org/package=survival
Kalbfleisch JD and Prentice RL (1980). The Statistical Analysis of Failure Time Data.
A synthetic replacement for the former diabetes dataset from the mlbench package. It has the same structure and number of observations but does not represent real people. Useful for demonstrating regression approaches for binary outcomes.
data_SynthDiabetesdata_SynthDiabetes
A data frame with 768 observations and 9 variables:
Number of times pregnant
Plasma glucose concentration (glucose tolerance test)
Diastolic blood pressure (mm Hg)
Triceps skin fold thickness (mm)
2-Hour serum insulin (mu U/ml)
Body mass index (BMI)
Diabetes pedigree function
Age in years
Factor indicating diabetes status (pos/neg)
mlbench::SynthDiabetes2, available in mlbench
version 2.1-11 or later.
Publication-ready summary of categorical and continuous variables (optionally stratified). Mimics the OG gtsummary style: * column headers include N, e.g. "Overall, N=200" * categorical rows shown as n (%) * continuous rows default to Median (IQR) (footnote reflects summary)
descriptive_table( data, exposures, by = NULL, percent = c("column", "row"), digits = 1, show_missing = c("ifany", "no"), show_dichotomous = c("all_levels", "single_row"), show_overall = c("no", "first", "last"), statistic = NULL, value = NULL, format = c("flextable", "gt"), theme = c("minimal") )descriptive_table( data, exposures, by = NULL, percent = c("column", "row"), digits = 1, show_missing = c("ifany", "no"), show_dichotomous = c("all_levels", "single_row"), show_overall = c("no", "first", "last"), statistic = NULL, value = NULL, format = c("flextable", "gt"), theme = c("minimal") )
data |
data.frame |
exposures |
Character vector of variables to summarise. Quoted names are recommended in scripts, and bare names are also accepted. |
by |
Optional single grouping variable. Quoted and bare names are accepted. |
percent |
"column" (default) or "row"; aliases like "col"/"rows" accepted |
digits |
integer; decimals for % and continuous stats (default 1) |
show_missing |
"ifany" (default) or "no" |
show_dichotomous |
"all_levels" (default) or "single_row" |
show_overall |
"no" (default), "first", or "last" |
statistic |
Optional summary type for numeric variables. Use a single
value such as |
value |
optional named list for single-row binaries (e.g., list(sex="Female")); formula entries like list(sex ~ "Female") are also accepted |
format |
"flextable" (default) or "gt" |
theme |
preset or primitives |
If variables have a "label" attribute, for example from
labelled::var_label(), those labels are used automatically in the
displayed table. Internal matching still uses the original column names.
A list with class c("gtregression", "descriptive_table", ...)
containing:
tableA gt_tbl or flextable.
table_displayDisplay-ready data.
table_bodyLong audit data with variable, level, and type.
variable_labelsNamed character vector of display labels used for variables.
Additional metadata fields.
Returns a tidy summary of each variable's structure, missingness, uniqueness, and suitability for use in regression models.
dissect(data, verbose = FALSE, format = c("flextable", "gt", "tibble"))dissect(data, verbose = FALSE, format = c("flextable", "gt", "tibble"))
data |
A data frame. |
verbose |
Logical; if |
format |
Output format. One of |
A tibble, gt_tbl, or flextable, depending on
format. The tibble has columns: Variable, Type, Missing (
Levels, Compatibility, and Hint.
dissect(data_birthwt, format = "tibble") dissect(data_birthwt, format = "gt") # Print notes that help interpret the data structure dissect(data_birthwt, verbose = TRUE, format = "tibble")dissect(data_birthwt, format = "tibble") dissect(data_birthwt, format = "gt") # Print notes that help interpret the data structure dissect(data_birthwt, verbose = TRUE, format = "tibble")
Creates the tabular input used by forest_reg() from uni_reg(),
multi_reg(), and optionally descriptive_table() objects. This
function is useful when users want to inspect, edit, or reuse the exact data
that will be passed to the forest plot. Stratified regression objects are
also supported when supplied one at a time; the returned data frame keeps the
characteristic rows once and places strata side by side as separate effect
columns for forest_reg().
forest_df(uni, multi = NULL, desc = NULL, digits = 2)forest_df(uni, multi = NULL, desc = NULL, digits = 2)
uni |
A |
multi |
Optional |
desc |
Optional descriptive table object from |
digits |
Number of digits used when formatting confidence intervals. |
A data frame with display columns, formatted effect-size columns,
standard-error columns, and plotting attributes used by forest_reg()
to draw confidence intervals.
birthwt_data <- data_birthwt |> dplyr::mutate( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) uni_or <- uni_reg( birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke", "ht"), approach = "logit" ) multi_or <- multi_reg( birthwt_data, outcome = "low", exposures = c("smoke", "ht"), adjust_for = c("age", "lwt"), approach = "logit" ) forest_data <- forest_df(uni_or, multi_or) head(forest_data)birthwt_data <- data_birthwt |> dplyr::mutate( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) uni_or <- uni_reg( birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke", "ht"), approach = "logit" ) multi_or <- multi_reg( birthwt_data, outcome = "low", exposures = c("smoke", "ht"), adjust_for = c("age", "lwt"), approach = "logit" ) forest_data <- forest_df(uni_or, multi_or) head(forest_data)
Wrapper around forestploter::forest() that works directly with
forest_df() output or with gtregression regression objects.
It can show descriptive columns and one or more model effect columns in a
table-style forest plot while leaving axis and interval drawing to
forestploter.
forest_reg( df = NULL, uni = NULL, multi = NULL, desc = NULL, theme = NULL, ci_col_width = 20, side = c("right", "left"), quiet = TRUE, effects = NULL, ticks_at = NULL, ticks_digits = NULL, xlim = NULL, style_strata = TRUE, strata_fill = "#EAF2F1", ... )forest_reg( df = NULL, uni = NULL, multi = NULL, desc = NULL, theme = NULL, ci_col_width = 20, side = c("right", "left"), quiet = TRUE, effects = NULL, ticks_at = NULL, ticks_digits = NULL, xlim = NULL, style_strata = TRUE, strata_fill = "#EAF2F1", ... )
df |
Output of |
uni, multi, desc
|
Optional |
theme |
Optional |
ci_col_width |
Numeric value, or one value per effect column,
controlling the blank spacer width used by |
side |
Character. For each effect, position of the plot relative to the effect-size text:
|
quiet |
Logical. Suppress forestploter warnings. Default = 'TRUE'. |
effects |
Optional effect labels passed to |
ticks_at |
Optional numeric vector, or list of numeric vectors for
multiple effect
columns, specifying x-axis tick positions. If |
ticks_digits |
Optional number of digits for x-axis tick labels. |
xlim |
Optional numeric vector of length 2, or list of length-2 numeric
vectors for multiple
effect columns, specifying x-axis limits. If |
style_strata |
Logical. Retained for older vertically grouped
stratified forest data. Current |
strata_fill |
Character. Fill color used for older styled stratum header rows. |
... |
Passed to |
A gtregression_forest object with elements:
plotThe forest plot object.
dataThe plotting data sent to forestploter::forest().
input_dataThe original forest_df() data, including
standard-error helper columns.
metaModel metadata, including reference line and x-axis transformation.
birthwt_data <- data_birthwt |> transform( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) uni_or <- uni_reg( birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke", "ht"), approach = "logit" ) multi_or <- multi_reg( birthwt_data, outcome = "low", exposures = c("smoke", "ht"), adjust_for = c("age", "lwt"), approach = "logit" ) forest_reg(uni = uni_or, multi = multi_or) # If axis labels overlap, set x-axis limits and tick marks. forest_reg( uni = uni_or, multi = multi_or, xlim = list(c(0.25, 8), c(0.25, 12)), ticks_at = list(c(0.5, 1, 2, 4, 8), c(0.5, 1, 2, 4, 8)) ) # If the forest plot panel is too narrow or too wide, tune ci_col_width. forest_reg( uni = uni_or, multi = multi_or, ci_col_width = c(18, 22) )birthwt_data <- data_birthwt |> transform( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) uni_or <- uni_reg( birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke", "ht"), approach = "logit" ) multi_or <- multi_reg( birthwt_data, outcome = "low", exposures = c("smoke", "ht"), adjust_for = c("age", "lwt"), approach = "logit" ) forest_reg(uni = uni_or, multi = multi_or) # If axis labels overlap, set x-axis limits and tick marks. forest_reg( uni = uni_or, multi = multi_or, xlim = list(c(0.25, 8), c(0.25, 12)), ticks_at = list(c(0.5, 1, 2, 4, 8), c(0.5, 1, 2, 4, 8)) ) # If the forest plot panel is too narrow or too wide, tune ci_col_width. forest_reg( uni = uni_or, multi = multi_or, ci_col_width = c(18, 22) )
Open a menu-driven Shiny app for common gtregression workflows: data import, descriptive tables, regression tables, survival analysis, diagnostics, causal mediation, plots, and exports.
gtregression_app(..., launch.browser = NULL)gtregression_app(..., launch.browser = NULL)
... |
Additional arguments passed to |
launch.browser |
Logical; passed to |
The app is intentionally kept out of the core package startup path. Shiny and
other interface packages are suggested dependencies and are loaded only when
gtregression_app() is called.
The Advanced tab includes a guided candidate-model builder. Users can name
two to six models, choose model-specific exposures and adjustment variables,
optionally add an interaction, and track a primary exposure. The app fits
compatible multi_reg(), cox_reg(), or surv_reg() objects
before passing them to compare_models(). Generated code records every
fitting call and the final comparison for reproducible use outside the app.
Invisibly returns the result of shiny::runApp().
compare_models(), multi_reg(), cox_reg(),
surv_reg()
if (interactive()) { gtregression_app() }if (interactive()) { gtregression_app() }
Review whether one or more candidate variables may act as confounders or effect modifiers for one or more exposures.
identify_confounder( data, outcome = NULL, exposure, potential_confounder, approach = "logit", time = NULL, event = NULL, distribution = "weibull", method = "change", threshold = 10, emm_threshold = 10, emm_test = c("interaction", "both", "estimate"), interaction_alpha = 0.05, format = c("flextable", "gt"), theme = c("minimal") )identify_confounder( data, outcome = NULL, exposure, potential_confounder, approach = "logit", time = NULL, event = NULL, distribution = "weibull", method = "change", threshold = 10, emm_threshold = 10, emm_test = c("interaction", "both", "estimate"), interaction_alpha = 0.05, format = c("flextable", "gt"), theme = c("minimal") )
data |
A data frame. |
outcome |
Outcome variable name. Quoted and bare names are accepted.
Required for ordinary regression approaches. Leave unset for Cox and
parametric survival approaches and supply |
exposure |
Exposure variable name(s). Can be a character scalar or vector. Quoted names are recommended in scripts, and bare names are also accepted. |
potential_confounder |
Candidate confounder/effect-modifier variable name(s). Can be a character scalar or vector. Quoted names are recommended in scripts, and bare names are also accepted. |
approach |
Regression approach. One of |
time |
Survival time variable name for |
event |
Event indicator variable name for survival approaches. Values may be coded as 0/1, 1/2, logical, or a two-level factor/character variable. |
distribution |
Parametric survival distribution for
|
method |
Confounding assessment method. One of |
threshold |
Percent change threshold for confounding assessment. |
emm_threshold |
Threshold for relative spread in stratum-specific estimates when using estimate-based effect-modification screening. |
emm_test |
One of |
interaction_alpha |
Alpha threshold for interaction p-values. |
format |
Output table format. One of |
theme |
Table theme preset or primitives. |
The function first assesses possible effect modification using stratum-specific estimates and/or an interaction test. If no important effect modification is detected, it then assesses confounding using the selected method.
This is a screening aid for viewing and organising results. Confounding and effect modification should be interpreted using subject-matter knowledge, study design, and causal diagrams such as DAGs. Automated change-in-estimate and interaction checks should not be used as the sole basis for model adjustment.
For each exposure-candidate pair, the interaction screen fits
outcome ~ exposure + potential_confounder +
exposure:potential_confounder. It does not adjust for other covariates.
Consequently, the reported interaction p-value is a candidate-only screening
result, not a final adjusted interaction analysis. Use
interaction_models(covariates = ...) when testing a planned,
covariate-adjusted interaction.
Use this function when you want to screen one or more candidate variables and
organise crude, adjusted, Mantel-Haenszel, and effect-modification signals in
one place. For a focused comparison of models with and without a planned
exposure-by-modifier interaction term, use interaction_models().
If a single exposure-candidate pair is supplied, returns a detailed list.
If multiple combinations are supplied, returns a list with:
A tibble with one row per exposure-candidate combination.
A named list of detailed results for each combination.
interaction_models() for focused model comparison of
a planned interaction term.
birthwt_data <- data_birthwt |> dplyr::mutate( low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")) ) identify_confounder( data = birthwt_data, outcome = low, exposure = smoke, potential_confounder = race, approach = logit ) lung_data <- data_lungcancer |> dplyr::mutate( trt = factor(trt, levels = c(1, 2), labels = c("Standard treatment", "Test treatment")), prior = factor(prior, levels = c(0, 10), labels = c("No", "Yes")) ) identify_confounder( data = lung_data, time = time, event = status, exposure = trt, potential_confounder = prior, approach = cox )birthwt_data <- data_birthwt |> dplyr::mutate( low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")) ) identify_confounder( data = birthwt_data, outcome = low, exposure = smoke, potential_confounder = race, approach = logit ) lung_data <- data_lungcancer |> dplyr::mutate( trt = factor(trt, levels = c(1, 2), labels = c("Standard treatment", "Test treatment")), prior = factor(prior, levels = c(0, 10), labels = c("No", "Yes")) ) identify_confounder( data = lung_data, time = time, event = status, exposure = trt, potential_confounder = prior, approach = cox )
Fits two models, one with and one without an interaction term between an exposure and a potential effect modifier. The models are compared using a likelihood ratio test or Wald test to assess statistical evidence of interaction.
interaction_models( data, outcome = NULL, exposure, covariates = NULL, effect_modifier, approach = "logit", time = NULL, event = NULL, distribution = "weibull", test = c("LRT", "Wald"), alpha = 0.05, verbose = FALSE, format = c("flextable", "gt", "tibble") )interaction_models( data, outcome = NULL, exposure, covariates = NULL, effect_modifier, approach = "logit", time = NULL, event = NULL, distribution = "weibull", test = c("LRT", "Wald"), alpha = 0.05, verbose = FALSE, format = c("flextable", "gt", "tibble") )
data |
A data frame containing all required variables. |
outcome |
Outcome variable name. Quoted and bare names are accepted.
Required for ordinary regression approaches. Leave unset for Cox and
parametric survival approaches and supply |
exposure |
Main exposure variable name. Quoted and bare names are accepted. |
covariates |
Optional character vector of adjustment covariates. They are included in both the model without and the model with the interaction term. Quoted names are recommended in scripts, and bare names are also accepted. |
effect_modifier |
Variable name for the potential effect modifier. Quoted and bare names are accepted. |
approach |
Regression approach. One of |
time |
Survival time variable name for |
event |
Event indicator variable name for survival approaches. |
distribution |
Parametric survival distribution for
|
test |
Statistical test for model comparison. One of |
alpha |
Significance threshold used to classify the interaction result. |
verbose |
Logical; if |
format |
Output format for the viewing table. One of
|
Use this function when the interaction is planned or clinically/causally
motivated and you want a focused model comparison. Mantel-Haenszel estimation
is not used here because this function tests an explicit interaction term in
a regression model. For broader screening of candidate confounders or effect
modifiers, including Mantel-Haenszel-supported checks when appropriate, use
identify_confounder().
With covariates = c(age, sex), the two fitted models are
outcome ~ exposure + effect_modifier + age + sex and
outcome ~ exposure + effect_modifier + age + sex +
exposure:effect_modifier. Both models use the same complete-case analysis
data, so covariate adjustment is applied consistently to the interaction
comparison.
A list with model objects, formulas, p-value, decision, and a
one-row summary tibble. When format is "gt" or
"flextable", the list also includes table.
identify_confounder() for broader confounding and
effect-modification screening.
birthwt_data <- data_birthwt |> dplyr::mutate( low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")) ) interaction_models( data = birthwt_data, outcome = low, exposure = smoke, effect_modifier = race, covariates = c(age, lwt), approach = logit ) lung_data <- data_lungcancer |> dplyr::mutate( trt = factor(trt, levels = c(1, 2), labels = c("Standard treatment", "Test treatment")), prior = factor(prior, levels = c(0, 10), labels = c("No", "Yes")) ) interaction_models( data = lung_data, time = time, event = status, exposure = trt, effect_modifier = prior, covariates = c(age, karno), approach = cox )birthwt_data <- data_birthwt |> dplyr::mutate( low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")) ) interaction_models( data = birthwt_data, outcome = low, exposure = smoke, effect_modifier = race, covariates = c(age, lwt), approach = logit ) lung_data <- data_lungcancer |> dplyr::mutate( trt = factor(trt, levels = c(1, 2), labels = c("Standard treatment", "Test treatment")), prior = factor(prior, levels = c(0, 10), labels = c("No", "Yes")) ) interaction_models( data = lung_data, time = time, event = status, exposure = trt, effect_modifier = prior, covariates = c(age, karno), approach = cox )
Plot observed survival over time, with optional confidence intervals, censoring marks, a log-rank p-value, and a number-at-risk table.
km_plot( data, time, event, by = NULL, conf.int = TRUE, risk_table = TRUE, p_value = TRUE, p_value_position = NULL, censor = TRUE, break_time_by = NULL, xlim = NULL, ylim = NULL, xlab = "Time", ylab = "Survival probability", title = NULL, subtitle = NULL, caption = NULL, title_size = NULL, title_face = "bold", legend_title = NULL, legend_position = NULL, palette = NULL, y_percent = TRUE, theme = "classic", grid = FALSE, base_size = 13 )km_plot( data, time, event, by = NULL, conf.int = TRUE, risk_table = TRUE, p_value = TRUE, p_value_position = NULL, censor = TRUE, break_time_by = NULL, xlim = NULL, ylim = NULL, xlab = "Time", ylab = "Survival probability", title = NULL, subtitle = NULL, caption = NULL, title_size = NULL, title_face = "bold", legend_title = NULL, legend_position = NULL, palette = NULL, y_percent = TRUE, theme = "classic", grid = FALSE, base_size = 13 )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
by |
Optional grouping variable for separate Kaplan-Meier curves. Quoted and bare names are accepted. |
conf.int |
Logical; if |
risk_table |
Logical; if |
p_value |
Logical; if |
p_value_position |
Optional numeric vector of length 2 giving the
|
censor |
Logical; if |
break_time_by |
Optional numeric interval for x-axis and risk-table time
breaks. If |
xlim |
Optional numeric vector of length 2 specifying x-axis limits. |
ylim |
Optional numeric vector of length 2 specifying y-axis limits.
Values may be supplied on the survival-probability scale
(for example |
xlab, ylab
|
Axis labels. |
title |
Optional plot title. |
subtitle |
Optional plot subtitle. |
caption |
Optional plot caption. |
title_size |
Optional numeric title font size. If |
title_face |
Font face for the title. One of |
legend_title |
Optional legend title. If |
legend_position |
Legend position. One of |
palette |
Optional character vector of colors for grouped curves. |
y_percent |
Logical; if |
theme |
Plot theme. One of |
grid |
Logical; if |
base_size |
Base font size. |
A ggplot2 object when risk_table = FALSE; otherwise a
patchwork object combining the survival curve and risk table. The
returned object has attributes fit, plot_data,
risk_table, and logrank_p.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) km_plot( data = lung_data, time = time, event = status ) km_plot( data = lung_data, time = time, event = status, by = trt, break_time_by = 200, ylim = c(50, 100), title = "A. Treatment group", title_size = 11, legend_position = "none" )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) km_plot( data = lung_data, time = time, event = status ) km_plot( data = lung_data, time = time, event = status, by = trt, break_time_by = 200, ylim = c(50, 100), title = "A. Treatment group", title_size = 11, legend_position = "none" )
Tabulate the number at risk at selected follow-up times.
km_risk_table( data, time, event, by = NULL, times, digits = 1, extend = TRUE, format = c("flextable", "gt", "tibble"), theme = c("minimal") )km_risk_table( data, time, event, by = NULL, times, digits = 1, extend = TRUE, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
by |
Optional grouping variable for separate Kaplan-Meier risk tables. Quoted and bare names are accepted. |
times |
Numeric vector of follow-up times for the risk table. |
digits |
Number of digits for displayed follow-up times. |
extend |
Logical. If |
format |
Output format. One of |
theme |
Table styling preset. |
The At risk column gives the number still under observation at each
requested time. The Events and Censored columns are interval
counts up to each requested time point as returned by
summary.survfit().
A list of class c("gtregression","km_risk_table", ...)
with elements:
tableA flextable, gt_tbl, or NULL
when format = "tibble".
table_bodyTibble with Kaplan-Meier risk table counts.
table_displayDisplay data frame used to render the table.
fitFitted survfit object.
time,event,by,times,format,sourceMetadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) km_risk_table( data = lung_data, time = time, event = status, by = trt, times = c(0, 90, 180, 365) ) km_risk_table( data = lung_data, time = "time", event = "status", times = c(0, 90, 180), format = tibble )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) km_risk_table( data = lung_data, time = time, event = status, by = trt, times = c(0, 90, 180, 365) ) km_risk_table( data = lung_data, time = "time", event = "status", times = c(0, 90, 180), format = tibble )
Compare survival curves between groups using the log-rank test.
logrank_test( data, time, event, by, digits = 2, format = c("flextable", "gt", "tibble"), theme = c("minimal") )logrank_test( data, time, event, by, digits = 2, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
by |
Grouping variable used to compare survival curves. Quoted and bare names are accepted. |
digits |
Number of digits for the chi-square statistic and expected events. |
format |
Output format. One of |
theme |
Table styling preset. |
The log-rank test compares the observed number of events with the expected
number of events in each group under the null hypothesis that the survival
curves are the same. It is a group comparison, not an effect-size estimate;
use cox_reg() when a hazard ratio is needed.
A list of class c("gtregression","logrank_test", ...) with
elements:
tableA flextable, gt_tbl, or NULL
when format = "tibble".
table_bodyTibble with group-level log-rank components and overall test statistics.
testOne-row tibble with chi-square statistic, degrees of freedom, and p-value.
fitThe survdiff object.
time,event,by,format,sourceMetadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) logrank_test( data = lung_data, time = time, event = status, by = trt ) logrank_test( data = lung_data, time = "time", event = "status", by = "trt", format = tibble )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) logrank_test( data = lung_data, time = time, event = status, by = trt ) logrank_test( data = lung_data, time = "time", event = "status", by = "trt", format = tibble )
Estimate direct, indirect, total, and proportion mediated effects from regression models.
mediation_analysis( data, exposure, mediator, outcome, covariates = NULL, mediator_approach = "linear", outcome_approach = "linear", exposure_value = NULL, reference_value = NULL, sims = 1000, conf_level = 0.95, seed = NULL, format = c("flextable", "gt"), theme = c("minimal") )mediation_analysis( data, exposure, mediator, outcome, covariates = NULL, mediator_approach = "linear", outcome_approach = "linear", exposure_value = NULL, reference_value = NULL, sims = 1000, conf_level = 0.95, seed = NULL, format = c("flextable", "gt"), theme = c("minimal") )
data |
A data frame. |
exposure |
Exposure/treatment variable. Quoted and bare names are accepted. |
mediator |
Mediator variable. Quoted and bare names are accepted. |
outcome |
Outcome variable. Quoted and bare names are accepted. |
covariates |
Optional character vector of covariate names. Quoted names are recommended in scripts, and bare names are also accepted. |
mediator_approach |
Mediator model. Currently |
outcome_approach |
Outcome model. One of |
exposure_value |
Exposure value used as the treatment level. If
|
reference_value |
Exposure value used as the reference level. If
|
sims |
Number of non-parametric bootstrap replicates used for confidence intervals. |
conf_level |
Confidence level for intervals. |
seed |
Optional random seed for reproducible bootstrap intervals. |
format |
One of |
theme |
Table theme. |
This function is for planned mediation questions, not automatic causal discovery. Causal interpretation requires the usual mediation assumptions, including no unmeasured exposure-outcome, exposure-mediator, or mediator-outcome confounding, correct temporal order, and suitable model specification. Use a directed acyclic graph (DAG) and subject-matter knowledge before interpreting the estimates causally.
For outcome_approach = "linear", effects are mean differences. For
outcome_approach = "logit", effects are predicted probability
differences, not odds ratios.
A list of class c("gtregression", "mediation_analysis", ...)
with elements:
A formatted flextable or gt_tbl.
Data frame of mediation effect estimates.
Formatted data frame used to build the table.
Fitted mediator and outcome models.
Bootstrap replicate estimates.
Reference and exposure values used.
Named character vector of display labels.
Matched function call.
med <- mediation_analysis( data = data_diabetes_mediation, exposure = obesity, mediator = glucose, outcome = diabetes, covariates = c(age, blood_pressure, pregnancies, diabetes_pedigree), outcome_approach = logit, sims = 50, seed = 123 ) med$table med$table_body # HTML-first output mediation_analysis( data = data_diabetes_mediation, exposure = obesity, mediator = glucose, outcome = diabetes, covariates = c(age, blood_pressure, pregnancies, diabetes_pedigree), outcome_approach = logit, format = gt, sims = 50, seed = 123 )$tablemed <- mediation_analysis( data = data_diabetes_mediation, exposure = obesity, mediator = glucose, outcome = diabetes, covariates = c(age, blood_pressure, pregnancies, diabetes_pedigree), outcome_approach = logit, sims = 50, seed = 123 ) med$table med$table_body # HTML-first output mediation_analysis( data = data_diabetes_mediation, exposure = obesity, mediator = glucose, outcome = diabetes, covariates = c(age, blood_pressure, pregnancies, diabetes_pedigree), outcome_approach = logit, format = gt, sims = 50, seed = 123 )$table
Merge gtregression tables and preserve structure and notes
merge_tables( ..., spanners = NULL, theme = "minimal", format = c("flextable", "gt") )merge_tables( ..., spanners = NULL, theme = "minimal", format = c("flextable", "gt") )
... |
Two or more |
spanners |
Character vector of spanner labels, one per table.
If |
theme |
Merge theme preset or vector of primitives. |
format |
Output table format. One of |
Binary variables should use the same row display across all input tables.
For a descriptive, univariable, and multivariable merge, the clearest
publication layout is usually show_dichotomous = "all_levels" in
descriptive_table() and show_ref = TRUE in each regression
function. Mixing these settings can create additional binary rows; in that
situation merge_tables() issues a warning with the compatible
settings.
Footnotes created by each input table are retained unchanged. Exact duplicate notes are shown once in the merged table.
A merged table object of class
c("gtregression", "merged_table", ...).
birthwt_data <- data_birthwt |> dplyr::mutate( race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) uni_tbl <- uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke", "ht"), approach = "logit" ) multi_tbl <- multi_reg( data = birthwt_data, outcome = "low", exposures = c("smoke", "ht"), adjust_for = c("age", "lwt"), approach = "logit" ) merge_tables( uni_tbl, multi_tbl, spanners = c("Univariable", "Adjusted") )birthwt_data <- data_birthwt |> dplyr::mutate( race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) uni_tbl <- uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke", "ht"), approach = "logit" ) multi_tbl <- multi_reg( data = birthwt_data, outcome = "low", exposures = c("smoke", "ht"), adjust_for = c("age", "lwt"), approach = "logit" ) merge_tables( uni_tbl, multi_tbl, spanners = c("Univariable", "Adjusted") )
Works with objects created by this package (class "gtregression"):
uni_reg(), multi_reg(), cox_reg(), surv_reg(),
stratified regression outputs, descriptive_table(), and
merge_tables().
No gtsummary dependency or fallback.
modify_table( gt_table, variable_labels = NULL, level_labels = NULL, header_labels = NULL, caption = NULL, bold_labels = TRUE, bold_levels = FALSE, italic_labels = FALSE, italic_levels = FALSE, remove_N = FALSE, remove_N_obs = FALSE, remove_abbreviations = FALSE, remove_adjustment_note = FALSE, caveat = NULL )modify_table( gt_table, variable_labels = NULL, level_labels = NULL, header_labels = NULL, caption = NULL, bold_labels = TRUE, bold_levels = FALSE, italic_labels = FALSE, italic_levels = FALSE, remove_N = FALSE, remove_N_obs = FALSE, remove_abbreviations = FALSE, remove_adjustment_note = FALSE, caveat = NULL )
gt_table |
Table object produced by this package (must contain
|
variable_labels |
Named character vector, for example
|
level_labels |
Named list for factor levels:
|
header_labels |
Named character vector to rename visible headers, e.g.
|
caption |
Optional caption/title. |
bold_labels |
Logical; bold variable (header) rows in the body. Defaults
to |
bold_levels |
Logical; bold factor level rows in the body. |
italic_labels |
Logical; italicize variable (header) rows in the body. |
italic_levels |
Logical; italicize factor level rows in the body. |
remove_N |
Logical; if |
remove_N_obs |
Logical; if |
remove_abbreviations |
Logical; if |
remove_adjustment_note |
Logical; if |
caveat |
Optional extra footnote. |
The modified table object (same class as input).
birthwt_data <- data_birthwt |> dplyr::mutate( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) tbl <- uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "smoke", "ht"), approach = "logit", format = "gt" ) modify_table( tbl, variable_labels = c(age = "Maternal age", smoke = "Smoking"), level_labels = list(smoke = c(Yes = "Smoker")), header_labels = c(estimate = "Crude OR", p.value = "P"), caption = "Univariable regression for low birth weight" )$tablebirthwt_data <- data_birthwt |> dplyr::mutate( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) tbl <- uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "smoke", "ht"), approach = "logit", format = "gt" ) modify_table( tbl, variable_labels = c(age = "Maternal age", smoke = "Smoking"), level_labels = list(smoke = c(Yes = "Smoker")), header_labels = c(estimate = "Crude OR", p.value = "P"), caption = "Univariable regression for low birth weight" )$table
Fit adjusted or multivariable regression models and return a manuscript-style table in flextable or gt format.
multi_reg( data, outcome, exposures, adjust_for = NULL, interaction = NULL, approach = "logit", format = c("flextable", "gt"), theme = c("minimal"), model_stats = FALSE, show_ref = TRUE )multi_reg( data, outcome, exposures, adjust_for = NULL, interaction = NULL, approach = "logit", format = c("flextable", "gt"), theme = c("minimal"), model_stats = FALSE, show_ref = TRUE )
data |
A |
outcome |
Character scalar; name of the outcome variable. Quoted and bare names are accepted. |
exposures |
Character vector; exposure variable(s) to report.
Quoted names are recommended in scripts, and bare names are also accepted.
If |
adjust_for |
Optional character vector of adjustment variables. Quoted
and bare names are accepted. Must not overlap with |
interaction |
Optional character scalar specifying one interaction term
using standard formula syntax, e.g. |
approach |
Character scalar specifying the regression approach.
One of |
format |
Output table format; one of |
theme |
Table styling preset (e.g. |
model_stats |
Logical; if |
show_ref |
Logical; if |
Use the default mode when you want all exposures in one model. Use
adjust_for when you want one adjusted estimate per reported exposure,
with the same adjustment set used repeatedly.
If exposure variables have a "label" attribute, for example from
labelled::var_label(), those labels are used automatically in the
displayed table and plots. Internal matching still uses the original column
names.
In default mode (adjust_for = NULL), all exposures are included in a
single multivariable model. In adjusted mode, one model is fitted per exposure,
adjusting for the variables specified in adjust_for.
Interaction terms specified via interaction are included in the model
using standard formula expansion (e.g. bmi*sex). Interaction effects are
displayed as additional rows beneath the corresponding exposure.
A list of class c("gtregression","multi_reg", ...) with elements:
A flextable (if format="flextable") or
gt_tbl (if format="gt").
A data frame of adjusted estimates and confidence intervals for each exposure and level.
A data frame used for rendering the final table, including header and level rows.
A list of fitted model(s).
summary() output for the fitted model(s).
Model-fit statistics when model_stats = TRUE;
otherwise NULL.
Named character vector of display labels used for exposure variables.
Regression diagnostics for linear models. Printing this element renders a publication-ready table; individual diagnostic rows remain available for programmatic use. Other approaches return a message.
The regression approach used.
The output format used.
Function identifier ("multi_reg").
Whether one adjusted model per exposure was fitted.
Adjustment variables supplied by the user, if any.
Exposure variables supplied by the user.
Interaction term supplied by the user, if any.
endometrial_data <- data_endometrial endometrial_data$HG <- factor(endometrial_data$HG, levels = c(0, 1)) endometrial_data$NV <- factor(endometrial_data$NV, levels = c(0, 1)) multi_reg(endometrial_data, HG, c(NV, PI, EH), approach = firth, format = gt)$tableendometrial_data <- data_endometrial endometrial_data$HG <- factor(endometrial_data$HG, levels = c(0, 1)) endometrial_data$NV <- factor(endometrial_data$NV, levels = c(0, 1)) multi_reg(endometrial_data, HG, c(NV, PI, EH), approach = firth, format = gt)$table
Draw the exposure, mediator, and outcome path from a
mediation_analysis() result.
plot_mediation(mediation_object, show_estimates = TRUE, base_size = 13)plot_mediation(mediation_object, show_estimates = TRUE, base_size = 13)
mediation_object |
Object returned by |
show_estimates |
Logical; if |
base_size |
Base font size. |
A ggplot2 object.
med <- mediation_analysis( data = data_diabetes_mediation, exposure = obesity, mediator = glucose, outcome = diabetes, covariates = c(age, blood_pressure, pregnancies, diabetes_pedigree), outcome_approach = logit, sims = 50, seed = 123 ) plot_mediation(med) plot_mediation(med, show_estimates = FALSE)med <- mediation_analysis( data = data_diabetes_mediation, exposure = obesity, mediator = glucose, outcome = diabetes, covariates = c(age, blood_pressure, pregnancies, diabetes_pedigree), outcome_approach = logit, sims = 50, seed = 123 ) plot_mediation(med) plot_mediation(med, show_estimates = FALSE)
Visualise model fit for fitted regression models and models stored inside
uni_reg() or multi_reg() results.
plot_model_fit( model, model_name = NULL, type = c("auto", "all", "residual", "qq", "scale_location", "cooks", "observed_predicted", "calibration"), bins = 10, base_size = 13 )plot_model_fit( model, model_name = NULL, type = c("auto", "all", "residual", "qq", "scale_location", "cooks", "observed_predicted", "calibration"), bins = 10, base_size = 13 )
model |
A fitted |
model_name |
Optional model name to select when |
type |
Plot type. One of |
bins |
Number of groups used for binomial calibration plots. |
base_size |
Base font size for the plot theme. |
plot_model_fit() is a visual check of how a fitted model behaves, not
a formal model-selection rule. For survival models, use check_ph() for Cox
proportional hazards diagnostics and plot_surv_fit() for parametric
survival model fit.
For binomial models, type = "calibration" compares grouped predicted
probabilities with observed event proportions. This is most informative for
multivariable models, where predictions vary across many patients. A
univariable binary predictor may produce only two calibration points; that is
expected and simply reflects the two fitted probabilities in the model.
Logistic residual plots often show two bands because the outcome is coded as
event/non-event.
A ggplot2 object for a single plot, or a patchwork object when
multiple diagnostics are requested.
fit_lm <- lm(mpg ~ wt + hp, data = mtcars) plot_model_fit(fit_lm) fit_glm <- glm(am ~ mpg + wt, data = mtcars, family = binomial()) plot_model_fit(fit_glm, type = calibration, bins = 4) uni_fit <- uni_reg(mtcars, am, c(mpg, wt), approach = logit) plot_model_fit(uni_fit, model_name = mpg, type = residual)fit_lm <- lm(mpg ~ wt + hp, data = mtcars) plot_model_fit(fit_lm) fit_glm <- glm(am ~ mpg + wt, data = mtcars, family = binomial()) plot_model_fit(fit_glm, type = calibration, bins = 4) uni_fit <- uni_reg(mtcars, am, c(mpg, wt), approach = logit) plot_model_fit(uni_fit, model_name = mpg, type = residual)
Draw a forest-style plot from a fitted gtregression object produced by
functions such as uni_reg(), multi_reg(), cox_reg(), or
surv_reg(). Stratified regression outputs are displayed as one
faceted quick-view plot; use forest_df() and forest_reg() for
publication-style stratified forest tables.
plot_reg( tbl, title = NULL, caption = NULL, ref_line = NULL, order_y = NULL, log_x = FALSE, xlim = NULL, breaks = NULL, point_color = "#6B7280", errorbar_color = "#6B7280", point_size = 2.8, point_stroke = 0.55, ci_linewidth = 0.55, base_size = 12, show_ref = NULL, sig_color = "#0072B2", sig_errorbar_color = "#0072B2", alpha = 0.05, show_adjustment_note = TRUE )plot_reg( tbl, title = NULL, caption = NULL, ref_line = NULL, order_y = NULL, log_x = FALSE, xlim = NULL, breaks = NULL, point_color = "#6B7280", errorbar_color = "#6B7280", point_size = 2.8, point_stroke = 0.55, ci_linewidth = 0.55, base_size = 12, show_ref = NULL, sig_color = "#0072B2", sig_errorbar_color = "#0072B2", alpha = 0.05, show_adjustment_note = TRUE )
tbl |
A fitted |
title |
Optional plot title. |
caption |
Optional plot caption. If |
ref_line |
Optional numeric value for the reference line. Defaults to 0 for linear models and 1 otherwise. |
order_y |
Optional character vector specifying exposure order. |
log_x |
Logical. If |
xlim |
Optional numeric vector of length 2 specifying x-axis limits. |
breaks |
Optional numeric vector of x-axis tick breaks. |
point_color |
Fill color for non-significant estimate points. |
errorbar_color |
Color for non-significant confidence intervals. |
point_size |
Diameter of estimate points in millimetres. |
point_stroke |
Outline width of estimate points. |
ci_linewidth |
Line width of confidence intervals. |
base_size |
Base font size. The default is designed for a clear report or slide figure; increase it for a single large plot. |
show_ref |
Logical or |
sig_color |
Optional fill color for significant points. |
sig_errorbar_color |
Optional color for significant error bars. |
alpha |
Significance level for linear models when |
show_adjustment_note |
Logical; if |
A ggplot2 object.
Creates two aligned forest plots from compatible gtregression
regression objects such as crude and adjusted outputs from uni_reg(),
multi_reg(), cox_reg(), or surv_reg().
plot_reg_combine( tbl_uni, tbl_multi, title_uni = NULL, title_multi = NULL, caption = NULL, ref_line = NULL, order_y = NULL, log_x = FALSE, point_color = "#6B7280", errorbar_color = "#6B7280", point_size = 2.8, point_stroke = 0.55, ci_linewidth = 0.55, base_size = 12, show_ref = NULL, sig_color = "#0072B2", sig_errorbar_color = "#0072B2", xlim_uni = NULL, breaks_uni = NULL, xlim_multi = NULL, breaks_multi = NULL, alpha = 0.05, show_adjustment_note = TRUE )plot_reg_combine( tbl_uni, tbl_multi, title_uni = NULL, title_multi = NULL, caption = NULL, ref_line = NULL, order_y = NULL, log_x = FALSE, point_color = "#6B7280", errorbar_color = "#6B7280", point_size = 2.8, point_stroke = 0.55, ci_linewidth = 0.55, base_size = 12, show_ref = NULL, sig_color = "#0072B2", sig_errorbar_color = "#0072B2", xlim_uni = NULL, breaks_uni = NULL, xlim_multi = NULL, breaks_multi = NULL, alpha = 0.05, show_adjustment_note = TRUE )
tbl_uni |
A univariate |
tbl_multi |
A multivariable |
title_uni, title_multi
|
Optional panel titles. |
caption |
Optional combined plot caption. If |
ref_line |
Optional numeric reference line. If |
order_y |
Optional character vector to customize exposure ordering. |
log_x |
Logical. If |
point_color, errorbar_color
|
Base colors for non-significant rows. |
point_size |
Diameter of estimate points in millimetres. |
point_stroke |
Outline width of estimate points. |
ci_linewidth |
Line width of confidence intervals. |
base_size |
Base font size for the plot theme. |
show_ref |
Logical or |
sig_color, sig_errorbar_color
|
Optional colors for significant rows.
If |
xlim_uni, breaks_uni
|
Optional x-axis limits and breaks for the univariate panel. |
xlim_multi, breaks_multi
|
Optional x-axis limits and breaks for the multivariable panel. |
alpha |
Significance level for linear models when |
show_adjustment_note |
Logical; if |
A patchwork object with two ggplot2 panels.
Compare the observed Kaplan-Meier survival curve with fitted parametric
survival curves from survival::survreg().
plot_surv_fit( data, time, event, by = NULL, adjust_for = NULL, distributions = c("weibull", "exponential", "lognormal", "loglogistic"), break_time_by = NULL, xlim = NULL, xlab = "Time", ylab = "Survival probability", title = NULL, legend_title = NULL, palette = NULL, base_size = 13, n_points = 200 )plot_surv_fit( data, time, event, by = NULL, adjust_for = NULL, distributions = c("weibull", "exponential", "lognormal", "loglogistic"), break_time_by = NULL, xlim = NULL, xlab = "Time", ylab = "Survival probability", title = NULL, legend_title = NULL, palette = NULL, base_size = 13, n_points = 200 )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
by |
Optional grouping variable for observed and fitted curves. Quoted and bare names are accepted. |
adjust_for |
Optional character vector of adjustment variables included in the fitted parametric model. Fitted curves are predicted at typical adjustment values. |
distributions |
Parametric survival distributions to overlay. One or
more of |
break_time_by |
Optional numeric interval for x-axis breaks. If
|
xlim |
Optional numeric vector of length 2 specifying x-axis limits. |
xlab, ylab
|
Axis labels. |
title |
Optional plot title. |
legend_title |
Optional legend title. If |
palette |
Optional character vector of colors for observed groups. |
base_size |
Base font size. |
n_points |
Number of points used to draw each fitted curve. |
plot_surv_fit() is a visual diagnostic for parametric survival
modelling. It is useful after surv_model_compare() and before treating
a final surv_reg() model as the preferred model. It is not a Cox-model
diagnostic; use check_ph() for Cox proportional hazards assumptions.
When adjust_for is supplied, fitted curves are predicted at typical
adjustment values: medians for numeric variables and the most common level for
categorical variables. Use this as a model-fit screen, not as a replacement
for clinical or subject-matter judgement.
A ggplot2 object with attributes km_fit,
model_fits, observed_data, fitted_data, and
prediction_data.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) plot_surv_fit( data = lung_data, time = time, event = status, by = trt, distributions = c(weibull, lognormal), break_time_by = 200 ) plot_surv_fit( data = lung_data, time = "time", event = "status", by = "trt", adjust_for = c(age, karno), distributions = "log-logistic" )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) plot_surv_fit( data = lung_data, time = time, event = status, by = trt, distributions = c(weibull, lognormal), break_time_by = 200 ) plot_surv_fit( data = lung_data, time = "time", event = "status", by = "trt", adjust_for = c(age, karno), distributions = "log-logistic" )
Prints the rendered table for any object produced by this package
(objects that include class "gtregression"), regardless of subtype
(uni_reg, multi_reg, stratified_*, merged_table,
descriptive_table, ...). If no rendered table is found, a compact
structure of the object (or its display data) is shown.
## S3 method for class 'gtregression' print(x, ...)## S3 method for class 'gtregression' print(x, ...)
x |
An object with class |
... |
Ignored. Present for compatibility with the generic. |
Estimate restricted mean survival time (RMST) up to a user-specified follow-up time. RMST is the average survival time observed within a fixed time window, such as 365 days.
rmst_table( data, time, event, by = NULL, tau, digits = 1, conf.level = 0.95, format = c("flextable", "gt", "tibble"), theme = c("minimal") )rmst_table( data, time, event, by = NULL, tau, digits = 1, conf.level = 0.95, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
by |
Optional grouping variable for separate RMST estimates. Quoted and bare names are accepted. |
tau |
Restriction time for RMST. For example, |
digits |
Number of digits for displayed survival time summaries. |
conf.level |
Confidence level for RMST confidence intervals. |
format |
Output format. One of |
theme |
Table styling preset. |
RMST is estimated from survival::survfit() using Kaplan-Meier methods
and summary.survfit(rmean = tau). When by has exactly two
groups, the table includes the RMST difference as the second group minus the
first group, with a Wald confidence interval and p-value based on the
reported RMST standard errors.
A list of class c("gtregression","rmst_table", ...) with
elements:
tableA flextable, gt_tbl, or NULL
when format = "tibble".
table_bodyTibble with numeric RMST summaries.
table_displayDisplay data frame used to render the table.
fitFitted survfit object.
time,event,by,tau,format,sourceMetadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) rmst_table( data = lung_data, time = time, event = status, by = trt, tau = 365 ) rmst_table( data = lung_data, time = "time", event = "status", tau = 180, format = tibble )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) rmst_table( data = lung_data, time = time, event = status, by = trt, tau = 365 ) rmst_table( data = lung_data, time = "time", event = "status", tau = 180, format = tibble )
Saves a collection of gtregression tables, merged tables,
gt_tbl/flextable objects, and ggplot2 plots into a
single Word document.
save_docx( tables = NULL, plots = NULL, filename = "report.docx", titles = NULL, table_width = 6.5, plot_width = 6, plot_height = 5 )save_docx( tables = NULL, plots = NULL, filename = "report.docx", titles = NULL, table_width = 6.5, plot_width = 6, plot_height = 5 )
tables |
A list of tables. Each element may be a |
plots |
A list of |
filename |
File name for the output, with or without |
titles |
Optional character vector of titles for tables and plots in the order they are added. |
table_width |
Maximum table width in inches for Word export. The default
|
plot_width |
Width of inserted plots in inches. |
plot_height |
Height of inserted plots in inches. |
Saves the Word document to disk. Invisibly returns the normalized file path.
birthwt_data <- data_birthwt |> dplyr::mutate( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) tbl <- uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "smoke"), approach = "logit", format = "flextable" ) save_docx(tables = tbl, filename = tempfile("report"))birthwt_data <- data_birthwt |> dplyr::mutate( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) tbl <- uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "smoke"), approach = "logit", format = "flextable" ) save_docx(tables = tbl, filename = tempfile("report"))
Saves a forest_reg() output, or a compatible
forestploter/grid object, to a fixed graphics device. This is useful
when the RStudio Viewer or operating-system graphics device crops wide forest
plots or compresses forest columns.
save_forest( forest, filename = "forest", format = c("pdf", "png", "tiff", "jpg"), width = NULL, height = NULL, scale = 1, auto_size = TRUE, padding = 0.25, dpi = 300 )save_forest( forest, filename = "forest", format = c("pdf", "png", "tiff", "jpg"), width = NULL, height = NULL, scale = 1, auto_size = TRUE, padding = 0.25, dpi = 300 )
forest |
A |
filename |
File name for the output, with or without extension. If no
directory is supplied, the file is saved in |
format |
Output format. One of |
width, height
|
Optional export width and height in inches. If either is
|
scale |
Positive multiplier applied to the export width and height. This is a quick way to make a large forest plot roomier. |
auto_size |
Logical. If |
padding |
White space around the forest plot in inches. |
dpi |
Resolution for raster formats. |
Saves the file to disk. Invisibly returns the normalized file path.
birthwt_data <- data_birthwt |> transform( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) uni_or <- uni_reg( birthwt_data, outcome = "low", exposures = c("age", "smoke", "ht"), approach = "logit" ) forest <- forest_reg(uni = uni_or) save_forest(forest, filename = tempfile("forest"), format = "pdf") # For large forest plots, increase width, height, scale, or padding. save_forest( forest, filename = tempfile("forest-wide"), format = "png", scale = 1.2, padding = 0.35, dpi = 300 )birthwt_data <- data_birthwt |> transform( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) uni_or <- uni_reg( birthwt_data, outcome = "low", exposures = c("age", "smoke", "ht"), approach = "logit" ) forest <- forest_reg(uni = uni_or) save_forest(forest, filename = tempfile("forest"), format = "pdf") # For large forest plots, increase width, height, scale, or padding. save_forest( forest, filename = tempfile("forest-wide"), format = "png", scale = 1.2, padding = 0.35, dpi = 300 )
Saves a ggplot2 plot to a file in PNG, PDF, or JPG format.
save_plot( plot, filename = "plot", format = c("png", "pdf", "jpg"), width = 8, height = 6, dpi = 300 )save_plot( plot, filename = "plot", format = c("png", "pdf", "jpg"), width = 8, height = 6, dpi = 300 )
plot |
A |
filename |
Name of the file to save, with or without extension. If no
directory is supplied, the file is saved in |
format |
Output format. One of |
width |
Width of the saved plot in inches. |
height |
Height of the saved plot in inches. |
dpi |
Resolution of the plot in dots per inch. |
Saves the file to disk. Invisibly returns the normalized file path.
p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() save_plot(p, filename = tempfile("plot"), format = "png")p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() save_plot(p, filename = tempfile("plot"), format = "png")
Saves a gtregression table, merged table, gt_tbl, or
flextable as a Word, RTF, PDF, or HTML file.
save_table( tbl, filename = "table", format = c("docx", "rtf", "pdf", "html"), orientation = c("auto", "portrait", "landscape"), fit_width = TRUE, font_size = 9, min_font_size = 8 )save_table( tbl, filename = "table", format = c("docx", "rtf", "pdf", "html"), orientation = c("auto", "portrait", "landscape"), fit_width = TRUE, font_size = 9, min_font_size = 8 )
tbl |
A |
filename |
File name for the output. Extension is optional. If no
directory is supplied, the file is saved in |
format |
Output format. One of |
orientation |
Word page orientation for DOCX output. One of
|
fit_width |
Logical. If |
font_size |
Requested font size for flextable DOCX output. |
min_font_size |
Smallest font size allowed when fitting wide flextable DOCX output. The font size is never reduced below this value. |
Saves the file to disk. Invisibly returns the normalized file path.
birthwt_data <- data_birthwt |> dplyr::mutate( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) tbl <- uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "smoke"), approach = "logit" ) save_table(tbl, filename = tempfile("table"), format = "html") # Wide Word tables can be saved in landscape orientation. save_table( tbl, filename = tempfile("table-wide"), format = "docx", orientation = "auto", fit_width = TRUE, font_size = 9, min_font_size = 8 )birthwt_data <- data_birthwt |> dplyr::mutate( smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) tbl <- uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "smoke"), approach = "logit" ) save_table(tbl, filename = tempfile("table"), format = "html") # Wide Word tables can be saved in landscape orientation. save_table( tbl, filename = tempfile("table-wide"), format = "docx", orientation = "auto", fit_width = TRUE, font_size = 9, min_font_size = 8 )
Compare candidate models added or removed stepwise, then return the accepted steps, model-fit metrics, and the lowest-AIC model.
select_models( data, outcome, exposures, approach = "logit", time = NULL, event = NULL, distribution = "weibull", direction = "forward", format = c("flextable", "gt", "tibble") )select_models( data, outcome, exposures, approach = "logit", time = NULL, event = NULL, distribution = "weibull", direction = "forward", format = c("flextable", "gt", "tibble") )
data |
A data frame containing the outcome and predictor variables. |
outcome |
A single character string indicating the outcome variable.
Quoted and bare names are accepted. Not used for survival approaches when
|
exposures |
Character vector of predictor variables to consider. Quoted names are recommended in scripts, and bare names are also accepted. |
approach |
Regression method. One of:
|
time, event
|
Survival time and event indicator for |
distribution |
Parametric survival distribution for
|
direction |
Stepwise selection direction. One of:
|
format |
Output format for the viewing table. One of
|
Treat stepwise selection as a screening tool. It is best used alongside the study question, clinical judgement, and model diagnostics rather than as an automatic final-model rule.
A list with the following components:
results_table: A tibble summarising each accepted step's
model metrics (AIC, BIC, deviance, log-likelihood, and adjusted R-squared
for linear models).
best_model: The best-fitting model object based on lowest AIC.
all_models: A named list of the accepted stepwise models.
direction: Stepwise selection direction used.
table: A formatted gt_tbl or flextable when
format is "gt" or "flextable".
data <- data_birthwt stepwise <- select_models( data = data, outcome = "bwt", exposures = c("age", "lwt", "smoke"), approach = "linear", direction = "forward" ) stepwise$results_table stepwise$best_modeldata <- data_birthwt stepwise <- select_models( data = data, outcome = "bwt", exposures = c("age", "lwt", "smoke"), approach = "linear", direction = "forward" ) stepwise$results_table stepwise$best_model
Fits multivariable regression models within each stratum and returns a unified wide table with one "Characteristic" column and, under bold spanners for each stratum, model N, "Adjusted <effect>", and "p-value".
stratified_multi_reg( data, outcome, exposures, stratifier, adjust_for = NULL, interaction = NULL, approach = "logit", format = c("flextable", "gt"), theme = c("minimal"), show_ref = TRUE )stratified_multi_reg( data, outcome, exposures, stratifier, adjust_for = NULL, interaction = NULL, approach = "logit", format = c("flextable", "gt"), theme = c("minimal"), show_ref = TRUE )
data |
A data frame containing the variables. |
outcome |
Character scalar; name of the outcome variable. Quoted and bare names are accepted. |
exposures |
Character vector of exposure variables to report. Quoted names are recommended in scripts, and bare names are also accepted. |
stratifier |
Character scalar; name of the stratifying variable. Quoted and bare names are accepted. |
adjust_for |
Optional character vector of adjustment variables.
Quoted and bare names are accepted. This argument works the same way as in
|
interaction |
Optional character scalar specifying one interaction term
using standard formula syntax, e.g. |
approach |
One of |
format |
One of |
theme |
Preset name (e.g. |
show_ref |
Logical; if |
If adjust_for = NULL, all exposures are included in one
multivariable model within each stratum. If adjust_for is supplied,
one adjusted model is fitted per exposure within each stratum.
If exposure variables have a "label" attribute, for example from
labelled::var_label(), those labels are used automatically in the
displayed table. Internal matching still uses the original column names.
A list of class c("gtregression","stratified_multi_reg", ...) with:
tableA flextable (format = "flextable") or
gt_tbl (format = "gt").
table_displayWide data frame used to build the table.
per_stratumNamed list of per-stratum regression results.
modelsNamed list of fitted models by stratum.
model_summariesNamed list of model summaries by stratum.
variable_labelsNamed character vector of display labels used for exposure variables.
reg_checkNamed list of diagnostics by stratum.
by, levels, approach, format, source
Metadata fields.
birthwt_data <- data_birthwt |> transform( race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), ui = factor(ui, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) stratified_multi <- stratified_multi_reg( data = birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke", "ht"), stratifier = "race", approach = "logit", format = "gt" ) stratified_adjusted <- stratified_multi_reg( data = birthwt_data, outcome = "low", exposures = c("smoke", "ht", "ui"), stratifier = "race", adjust_for = c("age", "lwt"), approach = "logit", format = "gt" )birthwt_data <- data_birthwt |> transform( race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")), ui = factor(ui, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) stratified_multi <- stratified_multi_reg( data = birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke", "ht"), stratifier = "race", approach = "logit", format = "gt" ) stratified_adjusted <- stratified_multi_reg( data = birthwt_data, outcome = "low", exposures = c("smoke", "ht", "ui"), stratifier = "race", adjust_for = c("age", "lwt"), approach = "logit", format = "gt" )
Fit univariable regression models within each level of a stratifier and combine the results into a stratified table rendered with gt or flextable.
stratified_uni_reg( data, outcome, exposures, stratifier, approach = "logit", format = c("flextable", "gt"), theme = c("minimal"), show_ref = TRUE )stratified_uni_reg( data, outcome, exposures, stratifier, approach = "logit", format = c("flextable", "gt"), theme = c("minimal"), show_ref = TRUE )
data |
A data frame containing the variables. |
outcome |
Character scalar; name of the outcome variable. Quoted and bare names are accepted. |
exposures |
Character vector of exposure variables to model. Quoted names are recommended in scripts, and bare names are also accepted. |
stratifier |
Character scalar; name of the stratifying variable. Quoted and bare names are accepted. |
approach |
Modeling approach. One of |
format |
Output table format; one of |
theme |
Table styling preset or theme primitives. |
show_ref |
Logical; if |
If exposure variables have a "label" attribute, for example from
labelled::var_label(), those labels are used automatically in the
displayed table. Internal matching still uses the original column names.
A list of class
c("gtregression", "stratified_uni_reg", ...) with elements:
tableA rendered gt_tbl or flextable.
table_displayDisplay-ready wide stratified results.
per_stratumList of complete uni_reg() results by
stratum.
modelsList of fitted model objects by stratum.
model_summariesList of model summaries by stratum.
variable_labelsNamed character vector of display labels used for exposure variables.
reg_checkRegression diagnostics by stratum.
byThe stratifier variable.
levelsStrata included in the analysis.
approachThe regression approach used.
formatThe output format used.
sourceFunction identifier
("stratified_uni_reg").
$tableRendered stratified regression table.
$table_displayWide display data used to build the table.
$per_stratumFull uni_reg() result objects by
stratum.
$modelsList of fitted model objects for each stratum.
$model_summariesList of model summaries.
$reg_checkDiagnostic check results (when applicable).
[multi_reg()], [plot_reg()], [identify_confounder()]
birthwt_data <- data_birthwt |> transform( race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) stratified_uni <- stratified_uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke"), stratifier = "race", approach = "logit", format = "gt" ) stratified_uni$tablebirthwt_data <- data_birthwt |> transform( race = factor(race, levels = c(1, 2, 3), labels = c("White", "Black", "Other")), smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")), low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")) ) stratified_uni <- stratified_uni_reg( data = birthwt_data, outcome = "low", exposures = c("age", "lwt", "smoke"), stratifier = "race", approach = "logit", format = "gt" ) stratified_uni$table
Fit the same parametric survival regression model using multiple distributions and compare model-fit statistics such as AIC and BIC.
surv_model_compare( data, time, event, exposures, adjust_for = NULL, distributions = c("weibull", "exponential", "lognormal", "loglogistic"), digits = 2, format = c("flextable", "gt", "tibble"), theme = c("minimal") )surv_model_compare( data, time, event, exposures, adjust_for = NULL, distributions = c("weibull", "exponential", "lognormal", "loglogistic"), digits = 2, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
exposures |
Character vector of main exposure variable names. Quoted names are recommended in scripts, and bare names are also accepted. |
adjust_for |
Optional character vector of adjustment variables. These variables are included in every candidate model. |
distributions |
Parametric survival distributions to compare. Defaults
to |
digits |
Number of digits for displayed model statistics. |
format |
Output format. One of |
theme |
Table styling preset. |
The same model formula is fitted for each candidate distribution using
survival::survreg(). Lower AIC or BIC values indicate better relative
model fit among the compared distributions. These statistics should be used
with clinical judgment and visual checks; they do not prove that a
distribution is scientifically correct.
A list of class c("gtregression","surv_model_compare", ...)
with elements:
tableA flextable, gt_tbl, or NULL
when format = "tibble".
table_bodyTibble with model-fit statistics.
table_displayDisplay data frame used to render the table.
modelsNamed list of fitted survreg models.
time,event,exposures,adjust_for,distributions,format,sourceMetadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) lung_data$prior <- factor(lung_data$prior, levels = c(0, 10), labels = c("No", "Yes")) surv_model_compare( data = lung_data, time = time, event = status, exposures = c("trt", "celltype", "prior"), adjust_for = c("age", "karno") ) surv_model_compare( data = lung_data, time = "time", event = "status", exposures = c(trt, prior), distributions = c(weibull, "log-logistic"), format = tibble )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) lung_data$prior <- factor(lung_data$prior, levels = c(0, 10), labels = c("No", "Yes")) surv_model_compare( data = lung_data, time = time, event = status, exposures = c("trt", "celltype", "prior"), adjust_for = c("age", "karno") ) surv_model_compare( data = lung_data, time = "time", event = "status", exposures = c(trt, prior), distributions = c(weibull, "log-logistic"), format = tibble )
Estimate model-based survival probabilities at user-specified follow-up
times from a fitted survival::survreg() model.
surv_predict( model, newdata = NULL, times, digits = 1, format = c("flextable", "gt", "tibble"), theme = c("minimal") )surv_predict( model, newdata = NULL, times, digits = 1, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
model |
A fitted |
newdata |
Optional |
times |
Numeric vector of follow-up times at which survival probability should be predicted. |
digits |
Number of digits for displayed follow-up times and probabilities. |
format |
Output format. One of |
theme |
Table styling preset. |
surv_predict() is for parametric survival regression models fitted by
surv_reg() or survival::survreg(). It is not a Kaplan-Meier
estimate and it is not a Cox prediction helper.
Supported distributions are "weibull", "exponential",
"lognormal", and "loglogistic", matching
surv_reg(). Predictions are conditional on the supplied profile and
the chosen parametric distribution.
A list of class c("gtregression","surv_predict", ...)
with elements:
tableA flextable, gt_tbl, or NULL
when format = "tibble".
table_bodyTibble with predicted survival probabilities.
table_displayDisplay data frame used to render the table.
modelThe fitted survreg model used for prediction.
newdata,times,distribution,format,sourceMetadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) fit <- surv_reg( data = lung_data, time = time, event = status, exposures = "trt", adjust_for = c("age", "karno"), distribution = weibull ) surv_predict( model = fit$models$trt, newdata = data.frame( trt = factor("Test", levels = levels(lung_data$trt)), age = 60, karno = 70 ), times = c(90, 180, 365) ) surv_predict( model = fit, times = c(90, 180), format = tibble )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) fit <- surv_reg( data = lung_data, time = time, event = status, exposures = "trt", adjust_for = c("age", "karno"), distribution = weibull ) surv_predict( model = fit$models$trt, newdata = data.frame( trt = factor("Test", levels = levels(lung_data$trt)), age = 60, karno = 70 ), times = c(90, 180, 365) ) surv_predict( model = fit, times = c(90, 180), format = tibble )
Fit parametric survival models and report time ratios.
surv_reg( data, time, event, exposures, adjust_for = NULL, stratifier = NULL, interaction = NULL, multivariable = FALSE, multivariate = NULL, distribution = "weibull", format = c("flextable", "gt"), theme = c("minimal"), show_sample = "events", model_stats = FALSE, show_ref = TRUE )surv_reg( data, time, event, exposures, adjust_for = NULL, stratifier = NULL, interaction = NULL, multivariable = FALSE, multivariate = NULL, distribution = "weibull", format = c("flextable", "gt"), theme = c("minimal"), show_sample = "events", model_stats = FALSE, show_ref = TRUE )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
exposures |
Character vector of exposure variable names. Quoted names are recommended in scripts, and bare names are also accepted. |
adjust_for |
Optional character vector of adjustment variables. When supplied, one adjusted model is fitted per exposure. |
stratifier |
Optional single stratifying variable. When supplied, stratum-specific parametric survival tables are produced using the same crude, adjusted, or multivariable workflow requested by the other arguments. The stratifier cannot also be used as the time, event, exposure, adjustment, or interaction variable. |
interaction |
Optional character scalar specifying one interaction term
using standard formula syntax, e.g. |
multivariable |
Logical; if |
multivariate |
Optional logical alias for |
distribution |
Parametric survival distribution. One of
|
format |
Output table format; one of |
theme |
Table styling preset. |
show_sample |
For stratified parametric survival tables, controls which
sample-size columns are shown in the publication table. One of
|
model_stats |
Logical; if |
show_ref |
Logical; if |
surv_reg() fits accelerated failure time style parametric survival
models using survival::survreg(). The exponentiated coefficient is
displayed as a time ratio. A time ratio above 1 suggests longer survival time;
a time ratio below 1 suggests shorter survival time, conditional on the chosen
distribution.
By default, surv_reg() keeps the exposure-by-exposure workflow:
without adjust_for, one crude model is fitted per exposure; with
adjust_for, one adjusted model is fitted per exposure and only the
exposure estimate is reported.
With multivariable = TRUE, all variables in exposures are
included in one parametric survival model and all coefficients are reported.
Since these estimates are adjusted for the other variables in the same model,
the table reports Adjusted Time Ratio (95% CI). The
adjust_for argument is not used in this mode; include every variable
that belongs in the model inside exposures.
Interaction terms specified via interaction are included using
standard formula expansion (for example, trt*prior). Interaction
effects are displayed as additional rows beneath the corresponding exposure.
Stratified parametric survival tables show event counts by default. Use
show_sample = "n", show_sample = "both", or
show_sample = "none" to control the displayed sample columns. Crude
stratified tables calculate these counts for each exposure-specific model;
adjusted and multivariable stratified tables use the corresponding fitted
model within each stratum.
If exposure variables have a "label" attribute, for example from
labelled::var_label(), those labels are used automatically in the
displayed table.
A list of class c("gtregression","surv_reg", ...) with elements:
A flextable or gt_tbl.
Data frame of time ratios and confidence intervals.
Data frame used to render the publication table.
List of fitted survreg models.
Summary output for the fitted models.
Model-fit statistics when model_stats = TRUE;
otherwise NULL.
Named character vector of display labels.
Character vector used by the rendered table. Adjustment notes use the same display labels as the table.
Metadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) lung_data$prior <- factor(lung_data$prior, levels = c(0, 10), labels = c("No", "Yes")) surv_reg( data = lung_data, time = time, event = status, exposures = c("trt", "celltype", "karno", "age") ) surv_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, prior), adjust_for = c(age, karno), distribution = lognormal ) # Interaction in an adjusted exposure model surv_reg( data = lung_data, time = time, event = status, exposures = trt, adjust_for = c(age, karno), interaction = trt*prior, distribution = weibull ) surv_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, prior, age, karno), distribution = weibull, multivariable = TRUE ) # multivariate is accepted as an alias surv_reg( data = lung_data, time = time, event = status, exposures = c(trt, age, karno), multivariate = TRUE )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) lung_data$prior <- factor(lung_data$prior, levels = c(0, 10), labels = c("No", "Yes")) surv_reg( data = lung_data, time = time, event = status, exposures = c("trt", "celltype", "karno", "age") ) surv_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, prior), adjust_for = c(age, karno), distribution = lognormal ) # Interaction in an adjusted exposure model surv_reg( data = lung_data, time = time, event = status, exposures = trt, adjust_for = c(age, karno), interaction = trt*prior, distribution = weibull ) surv_reg( data = lung_data, time = time, event = status, exposures = c(trt, celltype, prior, age, karno), distribution = weibull, multivariable = TRUE ) # multivariate is accepted as an alias surv_reg( data = lung_data, time = time, event = status, exposures = c(trt, age, karno), multivariate = TRUE )
Estimate Kaplan-Meier survival probabilities at user-specified follow-up times, such as 30-day, 6-month, or 1-year survival.
survival_prob( data, time, event, by = NULL, times, digits = 1, extend = TRUE, format = c("flextable", "gt", "tibble"), theme = c("minimal") )survival_prob( data, time, event, by = NULL, times, digits = 1, extend = TRUE, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
by |
Optional grouping variable for separate Kaplan-Meier survival probabilities. Quoted and bare names are accepted. |
times |
Numeric vector of follow-up times at which survival probability should be estimated. |
digits |
Number of digits for percentages and survival probabilities. |
extend |
Logical. If |
format |
Output format. One of |
theme |
Table styling preset. |
Survival probabilities are estimated from survival::survfit() at the
requested follow-up times. Events and censored counts are interval counts up
to each requested time point as returned by summary.survfit().
A list of class c("gtregression","survival_prob", ...)
with elements:
tableA flextable, gt_tbl, or NULL
when format = "tibble".
table_bodyTibble with Kaplan-Meier survival probabilities.
table_displayDisplay data frame used to render the table.
fitFitted survfit object.
time,event,by,times,format,sourceMetadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) survival_prob( data = lung_data, time = time, event = status, by = trt, times = c(90, 180, 365) ) survival_prob( data = lung_data, time = "time", event = "status", times = c(90, 180), format = tibble )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) survival_prob( data = lung_data, time = time, event = status, by = trt, times = c(90, 180, 365) ) survival_prob( data = lung_data, time = "time", event = "status", times = c(90, 180), format = tibble )
Estimate Kaplan-Meier survival time quantiles, such as the 25th percentile, median, and 75th percentile survival times.
survival_quantiles( data, time, event, by = NULL, probs = c(0.25, 0.5, 0.75), digits = 1, format = c("flextable", "gt", "tibble"), theme = c("minimal") )survival_quantiles( data, time, event, by = NULL, probs = c(0.25, 0.5, 0.75), digits = 1, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
by |
Optional grouping variable for separate Kaplan-Meier quantiles. Quoted and bare names are accepted. |
probs |
Numeric vector of event-time quantiles to estimate. The default
|
digits |
Number of digits for survival time summaries. |
format |
Output format. One of |
theme |
Table styling preset. |
A probability of 0.50 is the median event time: the estimated time by
which 50
A probability of 0.25 is the time by which 25
corresponding to 75
follow-up, the display table shows "Not reached".
A list of class c("gtregression","survival_quantiles", ...)
with elements:
tableA flextable, gt_tbl, or NULL
when format = "tibble".
table_bodyTibble with Kaplan-Meier quantiles.
table_displayDisplay data frame used to render the table.
fitFitted survfit object.
time,event,by,probs,format,sourceMetadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) survival_quantiles( data = lung_data, time = time, event = status, by = trt ) survival_quantiles( data = lung_data, time = "time", event = "status", probs = c(0.25, 0.5), format = tibble )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) survival_quantiles( data = lung_data, time = time, event = status, by = trt ) survival_quantiles( data = lung_data, time = "time", event = "status", probs = c(0.25, 0.5), format = tibble )
Summarise Kaplan-Meier follow-up with total N, events, censoring, and median survival with a 95
survival_summary( data, time, event, by = NULL, digits = 1, format = c("flextable", "gt", "tibble"), theme = c("minimal") )survival_summary( data, time, event, by = NULL, digits = 1, format = c("flextable", "gt", "tibble"), theme = c("minimal") )
data |
A |
time |
Survival follow-up time. Quoted and bare names are accepted. |
event |
Event indicator. Quoted and bare names are accepted. Numeric
|
by |
Optional grouping variable for separate Kaplan-Meier summaries. Quoted and bare names are accepted. |
digits |
Number of digits for survival time summaries. |
format |
Output format. One of |
theme |
Table styling preset. |
Median survival is estimated from survival::survfit(). If the median
survival time is not reached during follow-up, the display table shows
"Not reached".
A list of class c("gtregression","survival_summary", ...)
with elements:
tableA flextable, gt_tbl, or NULL
when format = "tibble".
table_bodyTibble with numeric Kaplan-Meier summaries.
table_displayDisplay data frame used to render the table.
fitFitted survfit object.
time,event,by,format,sourceMetadata fields.
lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) survival_summary( data = lung_data, time = time, event = status, by = trt ) survival_summary( data = lung_data, time = "time", event = "status", format = tibble )lung_data <- data_lungcancer lung_data$trt <- factor(lung_data$trt, levels = c(1, 2), labels = c("Standard", "Test")) survival_summary( data = lung_data, time = time, event = status, by = trt ) survival_summary( data = lung_data, time = "time", event = "status", format = tibble )
Fit one model per exposure and return a clean regression table in flextable or gt format.
uni_reg( data, outcome, exposures, approach = "logit", format = c("flextable", "gt"), theme = c("minimal"), model_stats = FALSE, show_ref = TRUE )uni_reg( data, outcome, exposures, approach = "logit", format = c("flextable", "gt"), theme = c("minimal"), model_stats = FALSE, show_ref = TRUE )
data |
A data frame containing the outcome and exposure variables. |
outcome |
Character scalar; outcome column name. Quoted and bare names are accepted. |
exposures |
Character vector; exposure column names. Quoted names are recommended in scripts, and bare names are also accepted. |
approach |
Regression approach. One of |
format |
One of |
theme |
Preset name (e.g. |
model_stats |
Logical; if |
show_ref |
Logical; if |
Use this when you want a quick crude association table before building an adjusted model. The fitted models are kept in the returned object, so the formatted table does not hide the underlying analysis.
If exposure variables have a "label" attribute, for example from
labelled::var_label(), those labels are used automatically in the
displayed table and plots. Internal matching still uses the original column
names.
A list of class c("gtregression","uni_reg", ...) with elements:
A flextable (when format="flextable") or
gt_tbl (when format="gt").
Data frame of numeric estimates and CIs.
Data frame for display (headers + levels).
List of fitted univariate models.
Per-model summary() results.
Model-fit statistics when model_stats = TRUE;
otherwise NULL.
Named character vector of display labels used for exposure variables.
Diagnostics for linear models. Printing this element renders a publication-ready table; individual diagnostic rows remain available for programmatic use. Other approaches return a message.
Metadata fields.
d <- mtcars if (requireNamespace("gt", quietly = TRUE)) { uni_reg(d, "am", c("mpg","cyl"), approach = "logit", format = "gt")$table } if (requireNamespace("flextable", quietly = TRUE)) { ft <- uni_reg(d, "am", c("mpg","cyl"), approach = "logit", format = "flextable") class(ft$table) } endometrial_data <- data_endometrial endometrial_data$HG <- factor(endometrial_data$HG, levels = c(0, 1)) endometrial_data$NV <- factor(endometrial_data$NV, levels = c(0, 1)) uni_reg(endometrial_data, HG, c(NV, PI, EH), approach = firth, format = gt)$tabled <- mtcars if (requireNamespace("gt", quietly = TRUE)) { uni_reg(d, "am", c("mpg","cyl"), approach = "logit", format = "gt")$table } if (requireNamespace("flextable", quietly = TRUE)) { ft <- uni_reg(d, "am", c("mpg","cyl"), approach = "logit", format = "flextable") class(ft$table) } endometrial_data <- data_endometrial endometrial_data$HG <- factor(endometrial_data$HG, levels = c(0, 1)) endometrial_data$NV <- factor(endometrial_data$NV, levels = c(0, 1)) uni_reg(endometrial_data, HG, c(NV, PI, EH), approach = firth, format = gt)$table