This function leverages gtsummary
and gt
to generate a publication-quality
summary table. It is designed to be robust, highly customizable, and easy
to integrate into R Markdown workflows for both HTML and PDF output.
create_table1(
data,
by_var,
vars,
font_size = NULL,
title = NULL,
subtitle = NULL,
footnote = NULL,
p_value = FALSE,
missing_text = "Unknown",
statistic = list(gtsummary::all_continuous() ~ "{median} ({p25}, {p75})"),
digits = NULL,
type = list(dplyr::where(is.numeric) ~ "continuous")
)
A data frame or tibble containing the data to summarize.
A character string specifying the stratifying column name. Required.
A character vector of column names to be summarized. Required.
A numeric value for the table's font size. gt
will handle
translation to appropriate units (e.g., px for HTML, pt for LaTeX).
Example: 10
. If NULL
(the default), gt
's standard size is used.
A character string for the table's main title.
A character string for the table's subtitle.
A character string for a source note or footnote.
Logical. If TRUE
, an overall p-value is added.
A character string to display for missing values.
A named list specifying the statistics to report.
A named list specifying the number of digits to display.
A named list of formulas specifying variable types. Default
list(where(is.numeric) ~ "continuous")
correctly handles all numeric variables.
A gt_tbl
object.
if (require(gtsummary) && require(gt) && require(dplyr)) {
# Example 1: Standard usage
create_table1(
data = gtsummary::trial,
by_var = "trt",
vars = c("age", "grade")
)
# Example 2: Using the font_size argument for a more compact table
create_table1(
data = gtsummary::trial,
by_var = "trt",
vars = c("age", "grade", "response", "marker"),
title = "Patient Demographics",
font_size = 9 # Set font size to 9pt
)
}
#> Loading required package: gtsummary
#> Loading required package: gt
#> Loading required package: dplyr
#>
#> Attaching package: ‘dplyr’
#> The following object is masked from ‘package:Biobase’:
#>
#> combine
#> The following objects are masked from ‘package:BiocGenerics’:
#>
#> combine, intersect, setdiff, union
#> The following objects are masked from ‘package:stats’:
#>
#> filter, lag
#> The following objects are masked from ‘package:base’:
#>
#> intersect, setdiff, setequal, union
Patient Demographics
Characteristic
Drug A
N = 981
Drug B
N = 1021
1 Median (Q1, Q3); n (%)