| Type: | Package |
| Title: | Tools for Creating Publication-Ready Regression Tables |
| Version: | 1.1.0 |
| 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. |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| Language: | en-US |
| LazyData: | true |
| Depends: | R (≥ 4.1.0) |
| Imports: | dplyr, risks, purrr, MASS, rlang, stats, lmtest, patchwork, ggplot2, utils, sandwich, tibble, broom, broom.helpers, gt, officer, flextable, scales (≥ 1.3.0), forestploter, logistf, survival |
| VignetteBuilder: | knitr |
| Suggests: | haven, mlbench (≥ 2.1-11), testthat (≥ 3.1.5), knitr, rmarkdown, car, forcats, pkgdown, ggtext, shiny, rstudioapi, DT, readxl, rio |
| Config/testthat/edition: | 3 |
| Config/Needs/website: | pkgdown |
| URL: | https://gtregression.thinkdenominator.com/, https://github.com/ThinkDenominator/gtregression |
| BugReports: | https://github.com/ThinkDenominator/gtregression/issues |
| Config/roxygen2/version: | 8.0.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-08-21 05:27:00 UTC; drrubesh |
| Author: | Rubeshkumar Polani
|
| Maintainer: | Rubeshkumar Polani <rubesh@thinkdenominator.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-08-21 07:30:02 UTC |
Access fields on gtregression objects with '$'
Description
Works for any object from this package, since they all carry class '"gtregression"'. Returns NULL (quietly) if the field is not present.
Usage
## S3 method for class 'gtregression'
x$name
Arguments
x |
A |
name |
Field name to access. |
Details
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)
Flextable builder for stratified MULTIVARIABLE wide tables (2 cols/stratum)
Description
Flextable builder for stratified MULTIVARIABLE wide tables (2 cols/stratum)
Usage
.build_flex_strata_wide_multi(df, spanners, effect_label_adj, theme, footnotes)
Flextable builder for stratified wide tables (3 cols per stratum)
Description
Flextable builder for stratified wide tables (3 cols per stratum)
Usage
.build_flex_strata_wide_uni(df, spanners, effect_label, theme, footnotes)
GT builder for stratified wide tables (3 cols per stratum)
Description
GT builder for stratified wide tables (3 cols per stratum)
Usage
.build_gt_strata_wide_uni(df, spanners, effect_label, theme, footnotes)
Fit Regression Model with One or More Predictors (Internal)
Description
Fits a regression model based on the selected approach. Can handle a single exposure or a vector of exposures.
Usage
.fit_uni_model(data, outcome, exposures, approach)
Arguments
data |
A 'data.frame' with complete observations for outcome and exposures. |
outcome |
A string. Name of the outcome variable. |
exposures |
A string or character vector of predictor(s). |
approach |
A string specifying the regression approach. One of '"logit"', '"firth"', '"logbinomial"', '"poisson"', '"linear"', '"robpoisson"', or '"negbin"'. |
Value
A fitted model object ('glm', 'logistf', 'lm', 'riskratio', or 'negbin') or 'NULL' if fitting fails.
Compose footnotes for multivariable strata (abbrev + per-stratum N)
Description
Compose footnotes for multivariable strata (abbrev + per-stratum N)
Usage
.footnotes_multi_strata(approach, fits_by_stratum, stratifier)
Compose footnotes for univariate strata
Description
Compose footnotes for univariate strata
Usage
.footnotes_uni_strata(approach)
Linear regression diagnostic checks (internal)
Description
Runs diagnostic checks for fitted linear regression models.
Usage
.reg_check_linear(model, exposure)
Arguments
model |
A fitted linear model ('lm' object). |
exposure |
Character string giving the name of the exposure variable for labeling. |
Details
The returned rows cover heteroskedasticity, residual normality, model specification, and influential observations. If a diagnostic cannot be computed for a given model, the function returns a clear "not available" result for that row instead of failing.
Value
A data frame with one row per diagnostic test, including:
- Exposure
Name of the exposure variable.
- Test
Diagnostic test name.
- Statistic
Test statistic or summary (e.g., p-values).
- Interpretation
Plain-language result interpretation.
Assemble wide display DF for all strata (univariate)
Description
Assemble wide display DF for all strata (univariate)
Usage
.strata_build_wide_uni(
data,
outcome,
exposures,
stratifier,
per_stratum,
variable_labels = NULL,
show_ref = TRUE
)
Get ordered levels for a stratifier
Description
Get ordered levels for a stratifier
Usage
.strata_levels(data, stratifier)
Pull (N, Effect, p) for a univariate stratum, aligned to a skeleton
Description
Pull (N, Effect, p) for a univariate stratum, aligned to a skeleton
Usage
.strata_pull_cols_uni(dlev, uni_res, skeleton, is_factor, exposures, outcome)
Validate Exposure Variable(s) for Regression
Description
Ensures that the exposure variable has at least two non-missing levels or sufficient numeric variation to support regression modelling.
Usage
.validate_exposures(data, exposures)
Arguments
data |
A data frame containing the exposure variables. |
exposures |
Character vector of column names to validate. |
Value
Returns TRUE if valid; otherwise throws an error.
Check collinearity using VIF for fitted models
Description
Computes Variance Inflation Factors (VIF) for fitted multivariable models
returned by multi_reg() or related functions.
Usage
check_collinearity(model, format = c("flextable", "gt", "tibble"))
Arguments
model |
A fitted model object returned by |
format |
Output format. One of |
Details
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.
Value
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 regression model convergence
Description
Check whether requested models converge, either one exposure at a time or as a single multivariable model.
Usage
check_convergence(
data,
exposures,
outcome,
approach = "logit",
multivariate = FALSE,
format = c("flextable", "gt", "tibble")
)
Arguments
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 |
Details
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.
Value
A data frame, gt_tbl, or flextable summarizing
convergence diagnostics, including:
ExposureName of the exposure variable.
ModelThe regression approach used.
ConvergedTRUEif the model converged successfully;FALSEotherwise.Max.prob.Maximum predicted probability or fitted value in the dataset.
See Also
[identify_confounder()], [interaction_models()]
Examples
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"
)
}
Check proportional hazards assumption for Cox models
Description
Test the proportional hazards assumption for fitted Cox proportional hazards models using Schoenfeld residuals.
Usage
check_ph(
model,
transform = c("km", "rank", "identity"),
alpha = 0.05,
format = c("flextable", "gt", "tibble")
)
Arguments
model |
A fitted |
transform |
Time transformation passed to |
alpha |
Significance level used for the simple interpretation column. |
format |
Output format. One of |
Details
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.
Value
A tibble, gt_tbl, or flextable with Schoenfeld
residual proportional hazards tests. The table contains:
ModelModel name. For a direct
coxphobject, this is"cox_model".TermModel term or
"GLOBAL".Chi.squareChi-square statistic.
dfDegrees of freedom.
p.valueTest p-value.
InterpretationSimple screening interpretation using
alpha.
Examples
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 Prespecified Regression Models
Description
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().
Usage
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")
)
Arguments
... |
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. |
Details
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.
Value
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
See Also
gtregression_app(), multi_reg(), cox_reg(),
surv_reg(), select_models()
Examples
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
)
Cox proportional hazards regression
Description
Fit Cox proportional hazards models and report hazard ratios.
Usage
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
)
Arguments
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 |
Details
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.
Value
A list of class c("gtregression","cox_reg", ...) with elements:
- table
A
flextableorgt_tbl.- table_body
Data frame of hazard ratios and confidence intervals.
- table_display
Data frame used to render the publication table.
- models
List of fitted
coxphmodels.- model_summaries
Summary output for the fitted models.
- model_stats
Model-fit statistics when
model_stats = TRUE; otherwiseNULL.- variable_labels
Named character vector of display labels.
- footnotes
Character vector used by the rendered table. Adjustment notes use the same display labels as the table.
- time,event,approach,format,source,adjust_for,exposures,interaction
Metadata fields.
Examples
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
)
Synthetic Diabetes Dataset
Description
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.
Usage
data_SynthDiabetes
Format
A data frame with 768 observations and 9 variables:
- pregnant
Number of times pregnant
- glucose
Plasma glucose concentration (glucose tolerance test)
- pressure
Diastolic blood pressure (mm Hg)
- triceps
Triceps skin fold thickness (mm)
- insulin
2-Hour serum insulin (mu U/ml)
- mass
Body mass index (BMI)
- pedigree
Diabetes pedigree function
- age
Age in years
- diabetes
Factor indicating diabetes status (pos/neg)
Source
mlbench::SynthDiabetes2, available in mlbench
version 2.1-11 or later.
Birth Weight Data
Description
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.
Usage
data_birthwt
Format
A data frame with 189 observations and 10 variables:
- low
Indicator for birth weight < 2500g (binary):
0 = normal,1 = low birth weight- age
Mother's age in years (numeric)
- lwt
Mother's weight in pounds at last menstrual period (numeric)
- race
Mother's race (factor):
1 = White,2 = Black,3 = Other- smoke
Smoking status during pregnancy (binary):
0 = No,1 = Yes- ptl
Number of previous premature labors (integer)
- ht
History of hypertension (binary):
0 = No,1 = Yes- ui
Presence of uterine irritability (binary):
0 = No,1 = Yes- ftv
no of physician visits during the 1st trimester (integer, 0–6)
- bwt
Birth weight in grams (numeric)
Details
The outcome variable is binary ('low'): birth weight < 2500g (yes = 1) or not (no = 0).
Source
Hosmer, D.W., Lemeshow, S. (1989). *Applied Logistic Regression.* New York: Wiley. Also available in MASS and described in detail in its documentation.
Diabetes Mediation Teaching Dataset
Description
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?
Usage
data_diabetes_mediation
Format
A data frame with variables:
- diabetes
Diabetes status (
No,Yes)- obesity
Obesity status based on BMI >= 30 (
No,Yes)- glucose
Plasma glucose concentration
- bmi
Body mass index
- age
Age in years
- blood_pressure
Diastolic blood pressure
- pregnancies
Number of pregnancies
- diabetes_pedigree
Diabetes pedigree function
Details
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.
Source
Derived from data_SynthDiabetes, which is based on
mlbench::SynthDiabetes2 (mlbench version 2.1-11 or later).
Endometrial Cancer Histology Grade Data
Description
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.
Usage
data_endometrial
Format
A data frame with 79 observations and 4 variables:
- NV
Neovascularization status (0 = absent, 1 = present)
- PI
Pulsatility index of the uterine artery
- EH
Endometrium height
- HG
Histology grade (0 = low grade, 1 = high grade)
Source
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).
References
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
Epilepsy Treatment and Seizure Counts
Description
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.
Usage
data_epilepsy
Format
A data frame with 236 observations and 9 variables:
- y
Number of seizures in a 2-week period (count)
- trt
Treatment group (factor):
placeboorprogabide- base
Seizure count during baseline period (numeric)
- age
Age of patient (numeric)
- V4
Indicator for 4th visit (binary)
- subject
Patient ID (factor)
- period
Follow-up period number (integer)
- lbase
Log of baseline seizures (numeric)
- lage
Log of age (numeric)
Source
MASS package. Original data from Thall and Vail (1990)
Student Absenteeism in Rural Schools
Description
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.
Usage
data_gt_quin
Format
A data frame with 146 observations and 5 variables:
- Eth
Ethnicity (
"A"= Aboriginal,"N"= Non-Aboriginal)- Sex
Sex (
"F"or"M")- Age
Age group (
"F0", "F1", "F2", "F3")- Lrn
Learner status (
"AL"= average learner,"SL"= slow learner)- Days
Number of days absent from school (count outcome)
Source
MASS package. See also Venables and Ripley (2002), *Modern Applied Statistics with S*.
Infertility Matched Case-Control Study
Description
investigating the relationship between infertility and abortions.
Usage
data_infertility
Format
A data frame with 248 observations and 8 variables:
- education
Education level (0 = 0–5 years, 1 = 6–11 years, 2 = 12+ years)
- age
Age in years
- parity
Number of prior pregnancies
- induced
Number of induced abortions
- case
Infertility case status (1 = case, 0 = control)
- spontaneous
Number of spontaneous abortions
- stratum
Matched set ID
- pooled.stratum
Pooled stratum ID used for conditional regression
Source
https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/infert.html
Lung Cancer Trial Data
Description
Survival data from a clinical trial of lung cancer patients conducted by the Veteran's Administration.
Usage
data_lungcancer
Format
A data frame with 137 observations and 8 variables:
- trt
Treatment group (1 = standard, 2 = test)
- celltype
Cell type (squamous, smallcell, adeno, large)
- time
Survival time (in days)
- status
Censoring status (1 = died, 0 = censored)
- karno
Karnofsky performance score (higher = better)
- diagtime
Months from diagnosis to randomization
- age
Age in years
- prior
Prior therapy (0 = no, 10 = yes)
Source
https://CRAN.R-project.org/package=survival
References
Kalbfleisch JD and Prentice RL (1980). The Statistical Analysis of Failure Time Data.
Descriptive Summary Table (no gtsummary) using gt/flextable
Description
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)
Usage
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")
)
Arguments
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 |
Details
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.
Value
A list with class c("gtregression", "descriptive_table", ...)
containing:
tableA
gt_tblorflextable.table_displayDisplay-ready data.
table_bodyLong audit data with variable, level, and type.
variable_labelsNamed character vector of display labels used for variables.
- metadata
Additional metadata fields.
Dissect a dataset before regression
Description
Returns a tidy summary of each variable's structure, missingness, uniqueness, and suitability for use in regression models.
Usage
dissect(data, verbose = FALSE, format = c("flextable", "gt", "tibble"))
Arguments
data |
A data frame. |
verbose |
Logical; if |
format |
Output format. One of |
Value
A tibble, gt_tbl, or flextable, depending on
format. The tibble has columns: Variable, Type, Missing (
Levels, Compatibility, and Hint.
Examples
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")
Build a compatible data frame for forest plots
Description
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().
Usage
forest_df(uni, multi = NULL, desc = NULL, digits = 2)
Arguments
uni |
A |
multi |
Optional |
desc |
Optional descriptive table object from |
digits |
Number of digits used when formatting confidence intervals. |
Value
A data frame with display columns, formatted effect-size columns,
standard-error columns, and plotting attributes used by forest_reg()
to draw confidence intervals.
Examples
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)
Draw a forest table from regression outputs
Description
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.
Usage
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",
...
)
Arguments
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 |
Value
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.
Examples
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)
)
Launch the gtregression app
Description
Open a menu-driven Shiny app for common gtregression workflows: data import, descriptive tables, regression tables, survival analysis, diagnostics, causal mediation, plots, and exports.
Usage
gtregression_app(..., launch.browser = NULL)
Arguments
... |
Additional arguments passed to |
launch.browser |
Logical; passed to |
Details
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.
Value
Invisibly returns the result of shiny::runApp().
See Also
compare_models(), multi_reg(), cox_reg(),
surv_reg()
Examples
if (interactive()) {
gtregression_app()
}
Identify confounders and effect modifiers
Description
Review whether one or more candidate variables may act as confounders or effect modifiers for one or more exposures.
Usage
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")
)
Arguments
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. |
Details
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().
Value
If a single exposure-candidate pair is supplied, returns a detailed list.
If multiple combinations are supplied, returns a list with:
- summary
A tibble with one row per exposure-candidate combination.
- details
A named list of detailed results for each combination.
See Also
interaction_models() for focused model comparison of
a planned interaction term.
Examples
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
)
Compare Models With and Without an Interaction Term
Description
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.
Usage
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")
)
Arguments
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
|
Details
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.
Value
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.
See Also
identify_confounder() for broader confounding and
effect-modification screening.
Examples
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
)
Kaplan-Meier survival plot
Description
Plot observed survival over time, with optional confidence intervals, censoring marks, a log-rank p-value, and a number-at-risk table.
Usage
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
)
Arguments
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. |
Value
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.
Examples
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"
)
Kaplan-Meier risk table
Description
Tabulate the number at risk at selected follow-up times.
Usage
km_risk_table(
data,
time,
event,
by = NULL,
times,
digits = 1,
extend = TRUE,
format = c("flextable", "gt", "tibble"),
theme = c("minimal")
)
Arguments
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. |
Details
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().
Value
A list of class c("gtregression","km_risk_table", ...)
with elements:
tableA
flextable,gt_tbl, orNULLwhenformat = "tibble".table_bodyTibble with Kaplan-Meier risk table counts.
table_displayDisplay data frame used to render the table.
fitFitted
survfitobject.time,event,by,times,format,sourceMetadata fields.
Examples
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
)
Log-rank test for Kaplan-Meier survival curves
Description
Compare survival curves between groups using the log-rank test.
Usage
logrank_test(
data,
time,
event,
by,
digits = 2,
format = c("flextable", "gt", "tibble"),
theme = c("minimal")
)
Arguments
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. |
Details
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.
Value
A list of class c("gtregression","logrank_test", ...) with
elements:
tableA
flextable,gt_tbl, orNULLwhenformat = "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
survdiffobject.time,event,by,format,sourceMetadata fields.
Examples
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
)
Causal mediation analysis
Description
Estimate direct, indirect, total, and proportion mediated effects from regression models.
Usage
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")
)
Arguments
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. |
Details
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.
Value
A list of class c("gtregression", "mediation_analysis", ...)
with elements:
- table
A formatted
flextableorgt_tbl.- table_body
Data frame of mediation effect estimates.
- table_display
Formatted data frame used to build the table.
- models
Fitted mediator and outcome models.
- boot
Bootstrap replicate estimates.
- values
Reference and exposure values used.
- variable_labels
Named character vector of display labels.
- call
Matched function call.
Examples
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
)$table
Merge gtregression tables and preserve structure and notes
Description
Merge gtregression tables and preserve structure and notes
Usage
merge_tables(
...,
spanners = NULL,
theme = "minimal",
format = c("flextable", "gt")
)
Arguments
... |
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 |
Details
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.
Value
A merged table object of class
c("gtregression", "merged_table", ...).
Examples
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")
)
Modify Regression/Descriptive Tables (labels, headers, caption, notes)
Description
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.
Usage
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
)
Arguments
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. |
Value
The modified table object (same class as input).
Examples
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"
)$table
Multivariable regression
Description
Fit adjusted or multivariable regression models and return a manuscript-style table in flextable or gt format.
Usage
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
)
Arguments
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 |
Details
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.
Value
A list of class c("gtregression","multi_reg", ...) with elements:
- table
A
flextable(ifformat="flextable") orgt_tbl(ifformat="gt").- table_body
A data frame of adjusted estimates and confidence intervals for each exposure and level.
- table_display
A data frame used for rendering the final table, including header and level rows.
- models
A list of fitted model(s).
- model_summaries
summary()output for the fitted model(s).- model_stats
Model-fit statistics when
model_stats = TRUE; otherwiseNULL.- variable_labels
Named character vector of display labels used for exposure variables.
- reg_check
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.
- approach
The regression approach used.
- format
The output format used.
- source
Function identifier (
"multi_reg").- adjusted_mode
Whether one adjusted model per exposure was fitted.
- adjust_for
Adjustment variables supplied by the user, if any.
- exposures
Exposure variables supplied by the user.
- interaction
Interaction term supplied by the user, if any.
Examples
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)$table
Plot mediation paths
Description
Draw the exposure, mediator, and outcome path from a
mediation_analysis() result.
Usage
plot_mediation(mediation_object, show_estimates = TRUE, base_size = 13)
Arguments
mediation_object |
Object returned by |
show_estimates |
Logical; if |
base_size |
Base font size. |
Value
A ggplot2 object.
Examples
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)
Plot model-fit diagnostics
Description
Visualise model fit for fitted regression models and models stored inside
uni_reg() or multi_reg() results.
Usage
plot_model_fit(
model,
model_name = NULL,
type = c("auto", "all", "residual", "qq", "scale_location", "cooks",
"observed_predicted", "calibration"),
bins = 10,
base_size = 13
)
Arguments
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. |
Details
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.
Value
A ggplot2 object for a single plot, or a patchwork object when
multiple diagnostics are requested.
Examples
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)
Plot regression estimates
Description
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.
Usage
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
)
Arguments
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 |
Value
A ggplot2 object.
Side-by-side forest plots: univariate vs multivariable
Description
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().
Usage
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
)
Arguments
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 |
Value
A patchwork object with two ggplot2 panels.
Plot observed and fitted parametric survival curves
Description
Compare the observed Kaplan-Meier survival curve with fitted parametric
survival curves from survival::survreg().
Usage
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
)
Arguments
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. |
Details
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.
Value
A ggplot2 object with attributes km_fit,
model_fits, observed_data, fitted_data, and
prediction_data.
Examples
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"
)
Print gtregression objects (unified)
Description
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.
Usage
## S3 method for class 'gtregression'
print(x, ...)
Arguments
x |
An object with class |
... |
Ignored. Present for compatibility with the generic. |
Print linear-regression diagnostics as a publication-ready table
Description
Print linear-regression diagnostics as a publication-ready table
Usage
## S3 method for class 'gtregression_reg_check'
print(x, ...)
Arguments
x |
A diagnostic list stored in a gtregression regression result. |
... |
Unused. |
Value
The diagnostic object, invisibly.
Restricted mean survival time table
Description
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.
Usage
rmst_table(
data,
time,
event,
by = NULL,
tau,
digits = 1,
conf.level = 0.95,
format = c("flextable", "gt", "tibble"),
theme = c("minimal")
)
Arguments
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. |
Details
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.
Value
A list of class c("gtregression","rmst_table", ...) with
elements:
tableA
flextable,gt_tbl, orNULLwhenformat = "tibble".table_bodyTibble with numeric RMST summaries.
table_displayDisplay data frame used to render the table.
fitFitted
survfitobject.time,event,by,tau,format,sourceMetadata fields.
Examples
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
)
Save multiple tables and plots to a Word document
Description
Saves a collection of gtregression tables, merged tables,
gt_tbl/flextable objects, and ggplot2 plots into a
single Word document.
Usage
save_docx(
tables = NULL,
plots = NULL,
filename = "report.docx",
titles = NULL,
table_width = 6.5,
plot_width = 6,
plot_height = 5
)
Arguments
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. |
Value
Saves the Word document to disk. Invisibly returns the normalized file path.
Examples
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"))
Save a forest_reg() output
Description
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.
Usage
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
)
Arguments
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. |
Value
Saves the file to disk. Invisibly returns the normalized file path.
Examples
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
)
Save a single plot
Description
Saves a ggplot2 plot to a file in PNG, PDF, or JPG format.
Usage
save_plot(
plot,
filename = "plot",
format = c("png", "pdf", "jpg"),
width = 8,
height = 6,
dpi = 300
)
Arguments
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. |
Value
Saves the file to disk. Invisibly returns the normalized file path.
Examples
p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) +
ggplot2::geom_point()
save_plot(p, filename = tempfile("plot"), format = "png")
Save a single regression or summary table
Description
Saves a gtregression table, merged table, gt_tbl, or
flextable as a Word, RTF, PDF, or HTML file.
Usage
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
)
Arguments
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. |
Value
Saves the file to disk. Invisibly returns the normalized file path.
Examples
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
)
Stepwise model selection with fit metrics
Description
Compare candidate models added or removed stepwise, then return the accepted steps, model-fit metrics, and the lowest-AIC model.
Usage
select_models(
data,
outcome,
exposures,
approach = "logit",
time = NULL,
event = NULL,
distribution = "weibull",
direction = "forward",
format = c("flextable", "gt", "tibble")
)
Arguments
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
|
Details
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.
Value
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 formattedgt_tblorflextablewhenformatis"gt"or"flextable".
Examples
data <- data_birthwt
stepwise <- select_models(
data = data,
outcome = "bwt",
exposures = c("age", "lwt", "smoke"),
approach = "linear",
direction = "forward"
)
stepwise$results_table
stepwise$best_model
Stratified multivariable regression
Description
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".
Usage
stratified_multi_reg(
data,
outcome,
exposures,
stratifier,
adjust_for = NULL,
interaction = NULL,
approach = "logit",
format = c("flextable", "gt"),
theme = c("minimal"),
show_ref = TRUE
)
Arguments
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 |
Details
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.
Value
A list of class c("gtregression","stratified_multi_reg", ...) with:
tableA
flextable(format ="flextable") orgt_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,sourceMetadata fields.
Examples
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"
)
Stratified univariable regression
Description
Fit univariable regression models within each level of a stratifier and combine the results into a stratified table rendered with gt or flextable.
Usage
stratified_uni_reg(
data,
outcome,
exposures,
stratifier,
approach = "logit",
format = c("flextable", "gt"),
theme = c("minimal"),
show_ref = TRUE
)
Arguments
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 |
Details
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.
Value
A list of class
c("gtregression", "stratified_uni_reg", ...) with elements:
tableA rendered
gt_tblorflextable.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").
Accessors
$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).
See Also
[multi_reg()], [plot_reg()], [identify_confounder()]
Examples
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$table
Compare parametric survival model distributions
Description
Fit the same parametric survival regression model using multiple distributions and compare model-fit statistics such as AIC and BIC.
Usage
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")
)
Arguments
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. |
Details
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.
Value
A list of class c("gtregression","surv_model_compare", ...)
with elements:
tableA
flextable,gt_tbl, orNULLwhenformat = "tibble".table_bodyTibble with model-fit statistics.
table_displayDisplay data frame used to render the table.
modelsNamed list of fitted
survregmodels.time,event,exposures,adjust_for,distributions,format,sourceMetadata fields.
Examples
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
)
Predict survival probabilities from a parametric survival model
Description
Estimate model-based survival probabilities at user-specified follow-up
times from a fitted survival::survreg() model.
Usage
surv_predict(
model,
newdata = NULL,
times,
digits = 1,
format = c("flextable", "gt", "tibble"),
theme = c("minimal")
)
Arguments
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. |
Details
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.
Value
A list of class c("gtregression","surv_predict", ...)
with elements:
tableA
flextable,gt_tbl, orNULLwhenformat = "tibble".table_bodyTibble with predicted survival probabilities.
table_displayDisplay data frame used to render the table.
modelThe fitted
survregmodel used for prediction.newdata,times,distribution,format,sourceMetadata fields.
Examples
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
)
Parametric survival regression
Description
Fit parametric survival models and report time ratios.
Usage
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
)
Arguments
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 |
Details
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.
Value
A list of class c("gtregression","surv_reg", ...) with elements:
- table
A
flextableorgt_tbl.- table_body
Data frame of time ratios and confidence intervals.
- table_display
Data frame used to render the publication table.
- models
List of fitted
survregmodels.- model_summaries
Summary output for the fitted models.
- model_stats
Model-fit statistics when
model_stats = TRUE; otherwiseNULL.- variable_labels
Named character vector of display labels.
- footnotes
Character vector used by the rendered table. Adjustment notes use the same display labels as the table.
- time,event,distribution,approach,format,source,adjust_for,exposures,interaction
Metadata fields.
Examples
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
)
Kaplan-Meier survival probability table
Description
Estimate Kaplan-Meier survival probabilities at user-specified follow-up times, such as 30-day, 6-month, or 1-year survival.
Usage
survival_prob(
data,
time,
event,
by = NULL,
times,
digits = 1,
extend = TRUE,
format = c("flextable", "gt", "tibble"),
theme = c("minimal")
)
Arguments
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. |
Details
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().
Value
A list of class c("gtregression","survival_prob", ...)
with elements:
tableA
flextable,gt_tbl, orNULLwhenformat = "tibble".table_bodyTibble with Kaplan-Meier survival probabilities.
table_displayDisplay data frame used to render the table.
fitFitted
survfitobject.time,event,by,times,format,sourceMetadata fields.
Examples
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
)
Kaplan-Meier survival quantile table
Description
Estimate Kaplan-Meier survival time quantiles, such as the 25th percentile, median, and 75th percentile survival times.
Usage
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")
)
Arguments
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. |
Details
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".
Value
A list of class c("gtregression","survival_quantiles", ...)
with elements:
tableA
flextable,gt_tbl, orNULLwhenformat = "tibble".table_bodyTibble with Kaplan-Meier quantiles.
table_displayDisplay data frame used to render the table.
fitFitted
survfitobject.time,event,by,probs,format,sourceMetadata fields.
Examples
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
)
Kaplan-Meier survival summary table
Description
Summarise Kaplan-Meier follow-up with total N, events, censoring, and median survival with a 95
Usage
survival_summary(
data,
time,
event,
by = NULL,
digits = 1,
format = c("flextable", "gt", "tibble"),
theme = c("minimal")
)
Arguments
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. |
Details
Median survival is estimated from survival::survfit(). If the median
survival time is not reached during follow-up, the display table shows
"Not reached".
Value
A list of class c("gtregression","survival_summary", ...)
with elements:
tableA
flextable,gt_tbl, orNULLwhenformat = "tibble".table_bodyTibble with numeric Kaplan-Meier summaries.
table_displayDisplay data frame used to render the table.
fitFitted
survfitobject.time,event,by,format,sourceMetadata fields.
Examples
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
)
Univariate regression
Description
Fit one model per exposure and return a clean regression table in flextable or gt format.
Usage
uni_reg(
data,
outcome,
exposures,
approach = "logit",
format = c("flextable", "gt"),
theme = c("minimal"),
model_stats = FALSE,
show_ref = TRUE
)
Arguments
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 |
Details
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.
Value
A list of class c("gtregression","uni_reg", ...) with elements:
- table
A
flextable(whenformat="flextable") orgt_tbl(whenformat="gt").- table_body
Data frame of numeric estimates and CIs.
- table_display
Data frame for display (headers + levels).
- models
List of fitted univariate models.
- model_summaries
Per-model
summary()results.- model_stats
Model-fit statistics when
model_stats = TRUE; otherwiseNULL.- variable_labels
Named character vector of display labels used for exposure variables.
- reg_check
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.
- approach, format, source
Metadata fields.
Examples
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)$table