| Type: | Package |
| Title: | Tools for Creating Publication-Ready Regression Tables |
| Version: | 1.2.0 |
| Description: | Simplifies regression modelling in R by integrating modelling, diagnostics, visualisation, and summary tools into a cohesive, user-friendly interface. Designed to be accessible for researchers, particularly those in Low- and Middle-Income Countries (LMIC). Supports logistic, linear, count, matched case-control, ordinal, multinomial, multilevel, Cox, parametric survival, and competing-risk regression, and absolute risk differences with the number needed to treat. 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, risk differences (Miettinen and Nurminen 1985 <doi:10.1002/sim.4780040211>), 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 (≥ 0.6.0), officer, flextable, scales (≥ 1.3.0), forestploter, logistf, survival, cmprsk, lme4, ordinal, nnet |
| VignetteBuilder: | knitr |
| Suggests: | haven, testthat (≥ 3.1.5), knitr, rmarkdown, car, ggtext, htmltools, jsonlite, 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-10-19 19:46:52 UTC; drrubesh |
| Author: | Rubeshkumar Polani
|
| Maintainer: | Rubeshkumar Polani <rubesh@thinkdenominator.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-10-20 13:30:15 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)
Value
The requested element of x, or NULL if x has
no element of that name. engine and format are treated as
aliases of each other.
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
Factor: level order (unused levels dropped by the callers' loops). Numeric and logical stratifiers are ordered by value; character stratifiers keep the order of first appearance.
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.
The returned table retains the underlying cox.zph diagnostics. Use
plot() to draw scaled Schoenfeld residual plots. When several models
were checked, select one by name or position with the model argument;
use term to draw a single model term.
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)
ph <- check_ph(cox_fit)
plot(ph, model = "trt")
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. Quoted and bare names are accepted; a bare name resolves
to a model variable first, not to a workspace object of the same name.
For Cox models this can be used to show the hazard ratio and its
percentage change across candidate models. "Change from first" is
|
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
)
Fine-Gray competing-risk regression
Description
Fit proportional subdistribution hazards models and return publication-ready subdistribution hazard ratios.
Usage
competing_risk_reg(
data,
time,
event,
event_of_interest,
exposures,
censor_code = 0,
adjust_for = NULL,
multivariable = FALSE,
multivariate = NULL,
format = c("flextable", "gt"),
theme = c("minimal"),
model_stats = FALSE,
show_ref = TRUE
)
Arguments
data |
A data frame containing follow-up time, event status, and model variables. |
time |
Numeric follow-up-time variable. Quoted and bare names work. |
event |
Event-status variable with one censoring code and distinct codes for the event of interest and competing events. |
event_of_interest |
Observed code or label for the event being modelled. |
exposures |
Variables whose effects are reported. |
censor_code |
Observed code or label for censoring. Defaults to '0'. |
adjust_for |
Optional adjustment variables. One adjusted model is fitted per exposure and only that exposure is reported. |
multivariable |
Logical; fit one model containing and reporting all variables in 'exposures'. |
multivariate |
Optional alias for 'multivariable'. |
format |
Output table format: '"flextable"' or '"gt"'. |
theme |
Table styling preset. |
model_stats |
Logical; return N, event counts, pseudo-log-likelihood, and convergence status. |
show_ref |
Logical; display categorical reference rows. |
Details
Each model uses the rows that are complete for its own variables. The N
column and the footnote report the observations and the events of interest
used by the fitted models, with the same wording as cox_reg() and
surv_reg().
Fine-Gray regression models the subdistribution hazard for the selected event. An SHR above 1 indicates a higher cumulative incidence of that event over follow-up, accounting for the presence of competing events. It is not a cause-specific Cox hazard ratio and should not be interpreted as one.
Value
A 'gtregression' object containing the publication table, numeric estimates, fitted 'crr' models, model summaries, and analysis metadata.
Examples
competing_risk_reg(
data_competing_risk,
time = follow_up_months,
event = outcome,
event_of_interest = Relapse,
censor_code = Censored,
exposures = c(treatment, age, stage)
)
Conditional logistic regression for matched case-control studies
Description
Fits conditional logistic regression models for individually or frequency matched case-control data and returns publication-ready matched odds ratios.
Usage
conditional_logit_reg(
data,
outcome,
exposures,
matched_set,
adjust_for = NULL,
multivariable = FALSE,
multivariate = NULL,
model_stats = FALSE,
format = c("flextable", "gt"),
theme = "minimal",
show_ref = TRUE
)
Arguments
data |
A data frame containing the outcome, predictors, and matched-set identifier. |
outcome |
Binary case-control outcome. The second factor/character level is treated as the case; numeric outcomes must use 0/1 or 1/2 coding. |
exposures |
Predictor names. Quoted and bare names are accepted. |
matched_set |
Variable identifying each matched case-control set. |
adjust_for |
Optional covariates. In exposure-by-exposure mode, each exposure is fitted with these covariates. |
multivariable |
Logical. If |
multivariate |
Optional alias for |
model_stats |
Logical. If |
format |
Output format: |
theme |
Table theme preset. |
show_ref |
Logical. Display reference rows for categorical predictors. |
Details
Matching is handled by conditioning on matched_set; no odds ratio is
estimated for that variable. Matched sets without both a case and a control
are not informative for conditional logistic regression and are excluded
with a message. This function is intended for matched case-control studies,
not complex survey analysis.
Value
A gtregression object containing the publication table,
underlying estimates, fitted clogit models, summaries, model
statistics, and matching metadata.
Examples
matched_data <- data.frame(
set = rep(1:8, each = 3),
case = rep(c(1, 0, 0), 8),
exposed = factor(rep(c("Yes", "No", "No"), 8),
levels = c("No", "Yes")),
age = rep(40:47, each = 3) + rep(c(0, -1, 1), 8)
)
conditional_logit_reg(
matched_data,
outcome = case,
exposures = exposed,
matched_set = set
)
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 = "both",
model_stats = FALSE,
show_ref = TRUE,
baseline_strata = NULL,
time_start = NULL,
cluster = NULL,
weights = NULL,
robust = NULL,
ties = c("efron", "breslow", "exact"),
control = NULL
)
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 ( |
model_stats |
Logical; if |
show_ref |
Logical; if |
baseline_strata |
Optional character vector of categorical variables
used to stratify the baseline hazard within one Cox model. Common hazard
ratios are estimated while each stratum has a separate baseline hazard.
No hazard ratio is estimated for these variables. This cannot be combined
with |
time_start |
Optional numeric variable containing entry or interval-start
times. When supplied, a counting-process response
|
cluster |
Optional variable identifying correlated observations. Cox models use a clustered sandwich variance estimate for this variable. |
weights |
Optional numeric case-weight variable. |
robust |
Optional logical passed to |
ties |
Method for handling tied event times: |
control |
Optional named list of arguments for
|
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.
baseline_strata fits one Cox model with separate baseline hazards for
the observed combinations of the selected categorical variables. It reports
common hazard ratios for the predictors and no coefficient for the strata.
This differs from stratifier, which fits separate models and reports
stratum-specific results.
The proportional hazards assumption should be assessed separately, for
example with check_ph().
Stratified Cox tables show both N and event counts by default
(show_sample = "both"). Use show_sample = "n",
show_sample = "events", or show_sample = "none" to control the
displayed sample columns. All counts are taken from the fitted model within
each stratum, so rows dropped for missing values in any model variable
(including time_start, cluster, and weights) are not
counted. When models within a stratum use different numbers of
observations, the footnote reports the range. Rows with a missing
stratifier value are excluded and counted in a footnote.
show_sample has no effect without stratifier.
Complete-case analysis is used: each model uses the rows that are complete
for its own variables. Unused factor levels are dropped for each fitted
model, so the reference category shown as "Ref." is the first level
present in the data used by that model. Ordered factors are analysed with
treatment (category-versus-reference) contrasts. Data in which every
observation is an event are accepted.
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,baseline_strata, 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
)
# One model with separate baseline hazards by cell type
cox_reg(
data = lung_data,
time = time,
event = status,
exposures = c(trt, age, karno),
baseline_strata = celltype,
multivariable = TRUE
)
# multivariate is accepted as an alias
cox_reg(
data = lung_data,
time = time,
event = status,
exposures = c(trt, age, karno),
multivariate = TRUE
)
Cumulative incidence plot for competing risks
Description
Estimate and plot the cumulative incidence of one event in the presence of competing events, with optional group comparison using Gray's test.
Usage
cuminc_plot(
data,
time,
event,
event_of_interest,
censor_code = 0,
by = NULL,
conf.int = TRUE,
p_value = TRUE,
p_value_position = NULL,
break_time_by = NULL,
xlim = NULL,
ylim = NULL,
xlab = "Time",
ylab = "Cumulative incidence",
title = NULL,
subtitle = NULL,
caption = NULL,
legend_title = NULL,
legend_position = NULL,
palette = NULL,
y_percent = TRUE,
theme = "classic",
grid = FALSE,
base_size = 13
)
Arguments
data |
A data frame containing follow-up time and event status. |
time |
Follow-up time. Quoted and bare column names are accepted. |
event |
Event-status variable with one censoring code and distinct codes for each event type. Quoted and bare column names are accepted. |
event_of_interest |
Code or label for the event to plot. This must be an observed value of 'event' and must differ from 'censor_code'. |
censor_code |
Code or label identifying censored observations. Defaults to '0'. |
by |
Optional single grouping variable. When supplied, separate curves
are drawn and Gray's test compares groups for the event of interest.
Groups are ordered by factor level (as in |
conf.int |
Logical; show pointwise 95 percent confidence intervals. |
p_value |
Logical; display Gray's test p-value when 'by' is supplied. |
p_value_position |
Optional numeric vector of length two giving the x and y coordinates of the p-value annotation. |
break_time_by |
Optional positive interval for x-axis breaks. |
xlim, ylim |
Optional numeric vectors of length two, given as
|
xlab, ylab |
Axis labels. |
title, subtitle, caption |
Optional plot text. |
legend_title |
Optional legend title. The display label of 'by' is used by default. |
legend_position |
One of '"bottom"', '"top"', '"right"', '"left"', or '"none"'. |
palette |
Optional character vector of curve colors. |
y_percent |
Logical; display cumulative incidence as percentages. |
theme |
One of '"classic"', '"minimal"', '"bw"', or '"light"'. |
grid |
Logical; show major grid lines. |
base_size |
Base font size. |
Details
Cumulative incidence estimates the absolute probability of the selected event over time while correctly retaining competing events in the risk process. Treating competing events as ordinary censoring with a Kaplan-Meier curve generally overestimates event probability.
Gray's test compares cumulative-incidence functions between groups. It is a group comparison and not an adjusted effect estimate; use 'competing_risk_reg()' when a subdistribution hazard ratio is required.
Value
A 'ggplot2' object with attributes 'fit', 'plot_data', 'gray_test', 'event_of_interest', and 'censor_code'.
Examples
cuminc_plot(
data_competing_risk,
time = follow_up_months,
event = outcome,
event_of_interest = Relapse,
censor_code = Censored,
by = treatment
)
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.
Synthetic Competing-Risk Oncology Dataset
Description
A synthetic clinical follow-up dataset for teaching cumulative incidence and competing-risk regression. The primary event is cancer relapse, while death before relapse is a competing event because it prevents a later relapse from being observed.
Usage
data_competing_risk
Format
A data frame with 500 observations and 8 variables:
- patient_id
Synthetic patient identifier.
- follow_up_months
Observed follow-up time in months.
- outcome
First observed outcome:
Censored,Relapse, orDeath without relapse.- treatment
Randomized treatment group:
StandardorIntervention.- age
Age at baseline in years.
- sex
Recorded sex:
FemaleorMale.- stage
Disease stage at baseline:
I,II, orIII.- performance_status
Baseline performance score from 0 to 2, with higher values indicating greater functional limitation.
Details
These data are entirely synthetic and do not correspond to real people. Latent times to relapse and death were generated from separate exponential event processes and compared with an independently generated censoring time. The intervention lowers the simulated relapse rate, while age, disease stage, and performance status influence one or both event processes. The dataset is intended for teaching workflow and interpretation, not for clinical inference or benchmarking estimators.
Source
Generated deterministically for the gtregression package.
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
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. If it is also listed in 'exposures', it is left out of the summarised variables, with a message. |
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". With "ifany", a "(Missing)" row (n and % of the column N) is added under every variable that has missing values, categorical or continuous. |
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. The value must be one of the observed levels of the variable. |
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.
Variable types: factor, character and logical variables are shown as
n (%) per level (logical: FALSE/TRUE); numeric variables
with exactly two distinct values are shown as categories; numeric variables
with a single distinct value are shown as one category (n, 100%) unless a
numeric statistic is requested for them; other numeric variables
are continuous. Levels of numeric variables shown as categories are sorted
by value. Date and date-time variables are not summarised: they are
excluded and named in a message.
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 = NULL, multi = NULL, desc = NULL, digits = 2)
Arguments
uni |
A |
multi |
Optional adjusted object of the same model family, for example
|
desc |
Optional descriptive table object from |
digits |
Number of digits used when formatting confidence intervals. |
Details
Effect columns use the same header as the source tables, for
example "Matched OR (95% CI)" for conditional_logit_reg() and
"Common OR (95% CI)" for ordinal_reg(), and the estimates and
intervals are taken unchanged from each result's table_body.
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 |
Deprecated and ignored. This argument never affected the rendered forest plot and is retained temporarily for backward compatibility. |
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 from the RStudio Addins menu
Description
The RStudio Addin (Addins > Regression without code (gtregression app)) opens the gtregression app in
an RStudio dialog window. It is the same application as
gtregression_app(), which opens it in your web browser.
Usage
gtregression_addin()
Details
There is no separate Addin interface: the interface, analyses, generated R
code and access to data frames in your global environment are identical to
gtregression_app(). Only the container differs (a 1200 x 800 RStudio
dialog instead of a browser window). The shiny and rstudioapi
packages are optional and are checked only when this function is called.
Selected data frames are copied into the app as read-only snapshots; the
source objects are not modified.
Value
Invisibly returns the result of shiny::runGadget().
See Also
Examples
if (
interactive() &&
requireNamespace("rstudioapi", quietly = TRUE) &&
rstudioapi::isAvailable()
) {
gtregression_addin()
}
Launch the gtregression app
Description
Open the gtregression app, the graphical interface for gtregression: data import and preparation, descriptive tables, regression tables, survival analysis, diagnostics, causal mediation, plots, exports and reproducible R code.
Usage
gtregression_app(..., launch.browser = NULL)
Arguments
... |
Additional arguments passed to |
launch.browser |
Passed to |
Details
gtregression_app() opens the gtregression app in your web browser. The
RStudio Addin (Addins > Regression without code (gtregression app)) opens exactly the same
application in an RStudio dialog window through
gtregression_addin(); only the window differs.
The app runs in your local R session, so data frames in your global environment can be chosen from the Data workspace (R Environment). Selected data are copied into the app as read-only snapshots; the source objects are not modified. Files can also be imported, and example data are included.
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
gtregression_addin, 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. The interaction p-value is a
likelihood-ratio test of the models with and without the interaction for
every approach except "robpoisson", where a robust (sandwich HC0)
Wald test is used because a likelihood-ratio test is not valid.
Percentage changes ("change-in-estimate") are computed on the displayed
ratio scale (OR, RR, IRR, HR, time ratio) as
100 * |adjusted - crude| / crude; for linear models the coefficients
are compared directly.
A numeric candidate coded as at most 10 distinct whole numbers is treated
as categorical in every step (adjusted model, interaction model,
stratum-specific estimates and Mantel-Haenszel). Other numeric candidates
are adjusted for as continuous and have no stratum-specific screen. The
estimate-spread screen only uses strata with at least 20 observations and a
stable estimate (converged model, finite standard error); the
stable column of stratum_estimates shows which strata were
used.
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
)
Import an analysis dataset
Description
Read common tabular data formats through one consistent interface. Optional packages are required only for the formats that use them.
Usage
import_data(
file,
format = NULL,
sheet = NULL,
header = TRUE,
sep = NULL,
na = c("", "NA"),
encoding = "UTF-8",
name_repair = c("check_unique", "unique", "minimal"),
...
)
Arguments
file |
Path to the data file. |
format |
Optional file format when it cannot be inferred from 'file'. Supply an extension without the leading dot, such as '"csv"' or '"dta"'. |
sheet |
Excel sheet name or number. Used only for '.xls' and '.xlsx' files. The first sheet is used by default. |
header |
Logical; whether delimited text files contain column names. |
sep |
Optional delimiter for '.csv', '.tsv', and '.txt' files. Defaults to comma for CSV, tab for TSV, and whitespace for TXT. |
na |
Character vector of strings interpreted as missing values. |
encoding |
Character encoding used for delimited text files. With the
default |
name_repair |
How to handle column names: '"check_unique"' preserves names and errors on blank or duplicated names; '"unique"' repairs them with [make.names()]; '"minimal"' preserves names without checking. |
... |
Additional arguments passed to the format-specific reader. |
Details
Supported extensions are CSV ('.csv'), tab-separated or text files ('.tsv', '.txt'), Excel ('.xls', '.xlsx'), R data ('.rds'), Stata ('.dta'), SPSS ('.sav', '.zsav', '.por'), and SAS ('.sas7bdat', '.xpt').
'readxl' is required for Excel files and 'haven' is required for Stata, SPSS, and SAS files. RDS files must contain a data frame or tibble.
Value
A data frame. Tibbles and labelled columns returned by 'readxl' or 'haven' are retained.
Examples
csv_file <- tempfile(fileext = ".csv")
utils::write.csv(
data.frame(outcome = c(0, 1), age = c(45, 61)),
csv_file,
row.names = FALSE
)
imported <- import_data(csv_file)
names(imported)
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: a preset ( |
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. With a logit outcome the effects are evaluated
with the mediator set to its predicted mean under each exposure value (the
mean is plugged into the outcome model). Because the logistic function is
non-linear this is an approximation to the effects obtained by averaging
over the mediator distribution; the table footnote states this.
Bootstrap replicates in which a model cannot be fitted are excluded from
the percentile intervals and p-values; a warning and the table footnote
report how many failed (also stored as boot_failed). The interval
column is labelled with conf_level.
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 two or more tables side by side
Description
Merge two or more tables side by side
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.
Tables of the same type can be merged directly. This is useful for
sensitivity analyses such as complete-case, best-case, and worst-case
models. Supply one table per scenario and use spanners to identify
each analysis; rows are aligned by their underlying variable and level.
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")
)
merge_tables(
multi_tbl,
multi_tbl,
spanners = c("Primary analysis", "Sensitivity analysis")
)
Modify table labels, headers, captions and 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. |
Details
For risk_difference() tables only the generic operations are
available: caption, caveat, variable_labels (outcome,
exposure and adjustment variables), level_labels (the two groups and
the event), header_labels and remove_abbreviations. The
other arguments are refused with an error and nothing is changed.
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.
For binary-outcome approaches ( |
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.
Confidence intervals are Wald intervals; for approach = "linear"
they use the t distribution with the residual degrees of freedom (as
confint() for lm). Factor exposures are always fitted with
treatment contrasts. Log-binomial models that fail with the default
starting values are refitted from the intercept log(mean(y)); if the
model still cannot be fitted the error names the approach and suggests
approach = "robpoisson".
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
Random-intercept multilevel regression
Description
Fit a linear or logistic mixed-effects model with one grouping variable and return publication-ready fixed-effect estimates.
Usage
multilevel_reg(
data,
outcome,
exposures,
group,
adjust_for = NULL,
approach = c("linear", "logit"),
format = c("flextable", "gt"),
theme = c("minimal"),
model_stats = FALSE,
show_ref = TRUE
)
Arguments
data |
A data frame containing the outcome, predictors, and group. |
outcome |
Continuous outcome for 'approach = "linear"' or binary outcome for 'approach = "logit"'. |
exposures |
Predictor variables to report. |
group |
Grouping variable for the random intercept. |
adjust_for |
Optional covariates included in the model but not reported. |
approach |
'"linear"' or '"logit"'. |
format |
Output table format: '"flextable"' or '"gt"'. |
theme |
Table styling preset. |
model_stats |
Logical; return model fit, clustering, random-effect, and ICC statistics. |
show_ref |
Logical; display categorical reference rows. |
Details
This intentionally focused workflow supports one random intercept. Random slopes, crossed effects, and nested random-effects formulas are outside this function's scope and should be fitted directly with specialist software.
For linear models, the ICC is the random-intercept variance divided by total random-intercept plus residual variance. For logistic models, a latent-scale ICC is calculated using residual variance pi-squared over three.
Value
A 'gtregression' object containing the publication table, numeric estimates, fitted mixed model, model statistics, and analysis metadata.
Examples
set.seed(71)
multilevel_data <- data.frame(
clinic = factor(rep(seq_len(20), each = 12)),
treatment = factor(rep(c("Control", "Intervention"), 120)),
age = rnorm(240, 58, 9)
)
clinic_effect <- rnorm(20, 0, 3)
multilevel_data$score <- 50 + 2 * (multilevel_data$treatment == "Intervention") +
0.2 * multilevel_data$age + clinic_effect[multilevel_data$clinic] + rnorm(240)
multilevel_reg(
multilevel_data,
outcome = score,
exposures = c(treatment, age),
group = clinic,
approach = linear,
model_stats = TRUE
)
Multinomial logistic regression
Description
Fit crude, exposure-specific adjusted, or joint multivariable multinomial logistic models for an unordered outcome with three or more categories.
Usage
multinomial_reg(
data,
outcome,
exposures,
adjust_for = NULL,
multivariable = FALSE,
multivariate = NULL,
model_stats = FALSE,
format = c("flextable", "gt"),
theme = "minimal",
show_ref = TRUE
)
Arguments
data |
A data frame containing the outcome and predictors. |
outcome |
An unordered factor outcome with at least three levels. The first level is the reference outcome category. |
exposures |
Predictor variables to report. |
adjust_for |
Optional covariates included but not reported. |
multivariable |
Logical; fit all exposures in one model. |
multivariate |
Optional alias for 'multivariable'. |
model_stats |
Logical; return model-fit and sample-size statistics. |
format |
Output table format: '"flextable"' or '"gt"'. |
theme |
Table styling preset. |
show_ref |
Logical; display categorical predictor reference rows. |
Details
Each odds ratio compares one non-reference outcome category with the first outcome level. Outcome categories are nominal: their order has no numeric or severity interpretation. Use 'relevel()' before fitting to choose another reference category.
Value
A 'gtregression' object containing a side-by-side table of outcome comparisons, fitted models, statistics, and one standard regression object per comparison in '$per_outcome'.
Examples
set.seed(1501)
example_data <- data.frame(
destination = factor(sample(c("Home", "Rehabilitation", "Hospital"), 120,
replace = TRUE),
levels = c("Home", "Rehabilitation", "Hospital")),
treatment = factor(sample(c("Control", "Intervention"), 120, TRUE)),
age = rnorm(120, 65, 10)
)
multinomial_reg(
example_data,
outcome = destination,
exposures = treatment,
adjust_for = age
)
Proportional-odds ordinal logistic regression
Description
Fit crude, exposure-specific adjusted, or joint multivariable proportional-odds models and return publication-ready common odds ratios.
Usage
ordinal_reg(
data,
outcome,
exposures,
adjust_for = NULL,
multivariable = FALSE,
multivariate = NULL,
assumption_test = TRUE,
model_stats = FALSE,
format = c("flextable", "gt"),
theme = "minimal",
show_ref = TRUE
)
Arguments
data |
A data frame containing the outcome and predictors. |
outcome |
An ordered-factor outcome. Its level order defines movement from lower to higher categories. |
exposures |
Predictor variables to report. |
adjust_for |
Optional covariates included but not reported. |
multivariable |
Logical; fit all exposures in one model. |
multivariate |
Optional alias for 'multivariable'. |
assumption_test |
Logical; perform term-level likelihood-ratio tests of the proportional-odds assumption. |
model_stats |
Logical; return model-fit and sample-size statistics. |
format |
Output table format: '"flextable"' or '"gt"'. |
theme |
Table styling preset. |
show_ref |
Logical; display categorical reference rows. |
Details
An odds ratio above one indicates greater odds of being in a higher outcome category, assuming the proportional-odds assumption holds. The outcome must be an ordered factor so category direction is never inferred silently.
Value
A 'gtregression' object containing the publication table, fitted models, common odds ratios, proportional-odds tests, and metadata.
Examples
ordinal_data <- data.frame(
recovery = ordered(
c("Poor", "Fair", "Good", "Excellent", "Fair", "Good"),
levels = c("Poor", "Fair", "Good", "Excellent")
),
treatment = factor(c("Control", "Control", "New", "New", "Control", "New")),
age = c(70, 64, 58, 51, 62, 55)
)
ordinal_reg(
ordinal_data,
outcome = recovery,
exposures = treatment,
adjust_for = age,
assumption_test = FALSE
)
Plot proportional hazards diagnostics
Description
Plot scaled Schoenfeld residual diagnostics retained by check_ph().
Usage
## S3 method for class 'gtregression_ph'
plot(x, model = NULL, term = NULL, ...)
Arguments
x |
An object returned by |
model |
Model to plot. Supply its name or position. This is required
when |
term |
Optional model term to plot. Supply its name or position. When omitted, all terms in the selected model are plotted. |
... |
Additional arguments passed to |
Value
The input object, invisibly.
Plot adjusted survival curves from a Cox model
Description
Plot model-based survival curves from a fitted Cox proportional hazards model at user-supplied or representative covariate profiles.
Usage
plot_cox_survival(
model,
model_name = NULL,
newdata = NULL,
by = NULL,
conf.int = TRUE,
break_time_by = NULL,
xlim = NULL,
xlab = "Time",
ylab = "Adjusted survival probability",
title = "Adjusted Cox survival curves",
legend_title = "Profile",
palette = NULL,
base_size = 13
)
Arguments
model |
A fitted |
model_name |
Model name or position when a |
newdata |
Optional data frame containing one covariate profile per curve. Row names are used as curve labels when available. |
by |
Optional model variable used to generate one curve per observed
level. Other model variables are held at representative values. Ignored
when |
conf.int |
Logical; display pointwise confidence bands. |
break_time_by |
Optional numeric interval for x-axis breaks. |
xlim |
Optional numeric vector of length 2 specifying x-axis limits. |
xlab, ylab |
Axis labels. |
title |
Optional plot title. |
legend_title |
Legend title. |
palette |
Optional character vector of curve colours. |
base_size |
Base font size. |
Details
For a model with a stratified baseline hazard, each covariate profile has a
different survival curve in every baseline stratum. One curve is therefore
drawn per profile and stratum: with a single profile the strata are
distinguished by colour; with several profiles, colour identifies the
profile and line type identifies the stratum. The stratum variables are not
covariates and cannot be used in by. If newdata contains the
stratum variables, each row is drawn only for its own stratum.
Value
A ggplot2 object with attributes survfit,
plot_data, and prediction_data. plot_data has one
row per time point and curve, with columns profile and
stratum identifying the curve.
Examples
lung_data <- data_lungcancer
lung_data$trt <- factor(lung_data$trt, levels = c(1, 2),
labels = c("Standard", "Test"))
fit <- cox_reg(
lung_data, time, status,
exposures = c(trt, age, karno),
multivariable = TRUE
)
plot_cox_survival(fit, by = trt)
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.
Plot crude and adjusted estimates side by side
Description
Creates two aligned forest plots from compatible gtregression
regression objects such as crude and adjusted outputs from uni_reg(),
multi_reg(), survival regression, or other supported model families.
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 |
The first |
tbl_multi |
The second |
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
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. |
Value
x, invisibly. Called for its side effect of printing the
rendered table.
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.
Risk difference between two groups
Description
Reports the absolute risk of a binary outcome in each of two groups and the risk difference between them, with a confidence interval and p-value, as a publication-ready table. The crude analysis uses the Miettinen-Nurminen score method; the adjusted analysis standardises the risks from a logistic regression model. Optionally the number needed to treat (NNTB / NNTH) is added.
Usage
risk_difference(
data,
outcome,
exposure,
adjust_for = NULL,
reference = NULL,
event = NULL,
event_type = NULL,
conf_level = 0.95,
format = "gt",
theme = NULL
)
Arguments
data |
A data frame. |
outcome |
Binary outcome column. Quoted and bare names are accepted. Logical, numeric 0/1 or 1/2, two-level factor, two-value character and value-labelled (haven) variables are supported. |
exposure |
Column defining exactly two groups (for example treatment arm or exposure status). Quoted and bare names are accepted. |
adjust_for |
Optional adjustment variables (quoted or bare names).
|
reference |
Group used as the reference. The risk difference is the
other (comparison) group minus the reference group. |
event |
Value of |
event_type |
|
conf_level |
Confidence level of the interval; default |
format |
|
theme |
Table theme: a preset name ( |
Details
Absolute risk and risk difference. The risk in a group is the
proportion of its members with the event. The risk difference (RD) is the
risk in the comparison group minus the risk in the reference group. It is
stored as a difference of proportions (for example -0.08) and shown
in percentage points (-8.0). A negative RD means that the event is
less frequent in the comparison group. For a harmful event (for example
death) a negative RD is an absolute risk reduction and a positive RD an
absolute risk increase; for a beneficial event (for example cure) the
reading is reversed. These are readings of the same number, not separate
estimates, and the table reports the signed RD only. The resolved event,
reference and comparison are stored in the result, are always written in
the table footnote, and are announced in a message whenever they were
inferred from anything other than logical or 0/1 coding.
Analysis population. One complete-case population is used: observations with a missing outcome or exposure (and, for the adjusted analysis, any missing adjustment variable) are excluded. The numbers supplied, analysed and excluded are stored and the footnote reports them.
Crude analysis (adjust_for = NULL). Risks are the observed
proportions. The confidence interval is the Miettinen-Nurminen score
interval (restricted maximum-likelihood variance with the
N/(N-1) factor, no continuity correction) and the p-value comes from
the same score statistic at a difference of zero (equal to Pearson's
chi-square multiplied by (N-1)/N). The method is defined when a
group has no events or only events; when no one, or everyone, has the
event the p-value is 1.
Adjusted analysis. A main-effects logistic regression of the outcome on the exposure and the adjustment variables is fitted. Each person's risk is predicted twice from their own covariates, once as a member of each group; the predictions are averaged over the analysis population to give the two adjusted (standardised) risks, and their difference is the adjusted RD. The table shows the observed events and group sizes next to the adjusted risks. The standard error is the influence-function standard error of the stacked estimating equations (logistic score equations and the two averages), which accounts for the estimation of the model and for the sampling of the covariates and does not rely on the logistic model being correct. The confidence interval is a Wald interval, with limits restricted to the range -1 to 1, and the p-value is two-sided normal. No small-sample correction is applied; in simulations with about 80 to 100 participants coverage of the 95% interval was about 94%. The analysis stops with an error, and returns no table, when the model does not converge, when fitted probabilities reach 0 or 1 (separation, including a group with no events or only events), when the exposure or an adjustment variable is aliased, or when the outcome is constant.
Interpretation. The function describes a calculation and makes no causal claim. In an individually randomised trial the adjusted RD is a covariate-adjusted estimate of the marginal treatment difference, and it remains valid when the logistic model is not exactly right (see the FDA 2023 guidance on covariate adjustment). In a non-randomised study it is a standardised risk difference; it can be read causally only if there is no unmeasured confounding, the outcome model is correct and the groups overlap in their covariates.
NNTB and NNTH. With event_type, the number needed to treat
is the reciprocal of the absolute value of the unrounded RD, shown rounded
up to a whole person. It is labelled NNTB (number needed to treat for one
additional person to benefit) when the comparison group does better and
NNTH (for one additional person to be harmed) when it does worse: for a
harmful event a negative RD gives NNTB and a positive RD NNTH, and the
reverse for a beneficial event. When the confidence interval of the RD
includes zero, the interval of the NNT runs from a finite NNTB through
infinity to a finite NNTH and is shown and stored in that form (Altman
1998), never as a pair of finite limits. The NNT applies to the follow-up
period of the study and assumes that the RD reflects what the intervention
does.
Limits of this version. Binary outcome at a fixed follow-up;
exactly two groups; independent observations; main-effects logistic model
for adjustment. Not supported: more than two groups, continuous exposures,
stratified (Mantel-Haenszel) or clustered designs, non-inferiority margins,
time-to-event outcomes. The result can be printed, saved with
save_table and relabelled with modify_table
(caption, caveat, labels and headers only); it is not accepted by
merge_tables or the forest-plot functions.
Value
A list of class c("risk_difference", "gtregression") with
elements:
- table
The rendered
gt_tblorflextable.- table_display
Data frame of the formatted cells as shown.
- table_body
Data frame of numeric results, one row per group (reference first):
group,events,n,risk,adjusted_risk,adjusted_risk_se,rd,rd_se,rd_low,rd_high,p_value. Risks and differences are proportions.rd_seis the influence-function standard error and isNAfor the crude analysis, whose score interval is not based on a single standard error.- footnotes
Character vector of table footnotes.
- analysis
"crude"or"adjusted".- outcome, exposure, adjust_for
Variable names.
- event, reference, comparison
Resolved event value and groups.
- event_type, conf_level
As supplied.
- method
List naming the estimate, interval, test and variance methods.
- n
List with the numbers of rows
supplied,analysedandexcluded.- nnt
NULL, or a list withtype("NNTB","NNTH"orNA),estimate(unrounded, may beInf),crosses_infinityandsegments(data frame withtype,from,to; two rows ending atInfwhen the interval runs through infinity).- model
The fitted logistic model (adjusted analysis), else
NULL. In the model the outcome is.rd_y(1 = event) and the exposure is.rd_a(1 = comparison group).- variable_labels, level_labels, theme
Labels and theme used for display.
- source, format
"risk_difference";"gt"or"flextable".
References
Miettinen O, Nurminen M (1985). Comparative analysis of two rates. Statistics in Medicine, 4(2), 213-226.
Newcombe RG (1998). Interval estimation for the difference between independent proportions: comparison of eleven methods. Statistics in Medicine, 17(8), 873-890.
Altman DG (1998). Confidence intervals for the number needed to treat. BMJ, 317(7168), 1309-1312.
U.S. Food and Drug Administration (2023). Adjusting for Covariates in Randomized Clinical Trials for Drugs and Biological Products: Guidance for Industry.
See Also
uni_reg and multi_reg for relative
measures (odds ratios, risk ratios).
Examples
# Crude: low birth weight by maternal smoking
rd <- risk_difference(data_birthwt, low, smoke)
rd$table_display
rd$footnotes
# Adjusted (standardised), with the number needed to treat
adj <- risk_difference(
data_birthwt, "low", "smoke",
adjust_for = c("age", "lwt"),
event_type = "harmful",
format = "flextable"
)
adj$table_display
adj$table_body
adj$nnt
# Factor coding: name the event and the reference explicitly
bw <- data_birthwt
bw$smoking <- factor(bw$smoke, levels = c(0, 1), labels = c("No", "Yes"))
bw$weight <- factor(bw$low, levels = c(0, 1), labels = c("Normal", "Low"))
risk_difference(bw, weight, smoking, event = "Low", reference = "No",
conf_level = 0.90)$table_display
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. The
column headers show the level used, for example |
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.
Information criteria are only comparable between models fitted to the same
observations. select_models() therefore restricts the data to
complete cases across the outcome (or time and event) and
all candidate variables before selection, reports the N used and the number
of rows excluded in a message and in the table note, and stores them as
n_used and n_excluded. Backward (and stepwise) selection can
remove the last variable and so reach the intercept-only model.
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. -
n_used,n_excluded: number of complete cases used for every candidate model and number of rows excluded because of missing values in the outcome or any candidate variable. -
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.
For binary-outcome approaches ( |
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.
For binary-outcome approaches ( |
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 = "both",
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
( |
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 both N and event counts by
default (show_sample = "both"). Use show_sample = "n",
show_sample = "events", or show_sample = "none" to control the
displayed sample columns. All counts are taken from the fitted model within
each stratum. When models within a stratum use different numbers of
observations, the footnote reports the range. Rows with a missing
stratifier value are excluded and counted in a footnote.
show_sample has no effect without stratifier.
Complete-case analysis is used: each model uses the rows that are complete
for its own variables. Unused factor levels are dropped for each fitted
model, so the reference category shown as "Ref." is the first level
present in the data used by that model. Ordered factors are analysed with
treatment (category-versus-reference) contrasts. Data in which every
observation is an event are accepted; follow-up times must be greater than
zero.
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
)
Univariable 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.
For binary-outcome approaches ( |
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.
Confidence intervals are Wald intervals; for approach = "linear"
they use the t distribution with the residual degrees of freedom (as
confint() for lm), consistent with the t-based p-values.
Factor exposures are always fitted with treatment contrasts (each level
versus the reference), whatever options(contrasts = ) or a
contrasts attribute says. An exposure whose model cannot be fitted
is kept in the table with a dash and named in a footnote and in
failed_exposures.
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