Create Summary Tables Using table1 with Custom Formatting
Source:R/margot_make_tables.R
margot_make_tables.Rd
margot_make_tables
is a wrapper for table1::table1()
which simplifies the creation of summary tables.
It provides custom variable labelling, formatting, factor conversion, and additional table options.
This function is optimized for "markdown"
, "latex"
, and "flextable"
outputs, with special support for Quarto documents.
Arguments
- data
A
data.frame
containing the dataset.- vars
A character vector of variable names to include on the left-hand side of the table.
- by
A character vector of variable names to stratify the table by. Supports multiple variables for interactions.
- labels
A named character vector for custom variable labels. Names should correspond to variable names in
vars
.- factor_vars
An optional character vector of variable names in
vars
to convert to factors for frequency tables.- table1_opts
A list of additional options to pass to
table1::table1()
. For example,list(overall = FALSE, transpose = TRUE)
.- format
A character string specifying the output format. Options are
"markdown"
(default),"latex"
, or"flextable"
.- kable_opts
A list of additional options controlling table styling:
For
format = "latex"
, these are passed tokableExtra::kable_styling()
.For
format = "markdown"
, currently only for documentation purposes.
- flex_opts
A list of additional options for flextable formatting:
font_size
: Font size for the table (default: 9)font_size_header
: Font size for headers (default: 10)theme
: Theme function to apply (default: "theme_vanilla")autofit
: Whether to autofit columns (default: TRUE)width
: Table width (0-1 for proportion of page width, default: 1)
- quarto_label
An optional label for Quarto cross-references (e.g., "tbl-demographics"). When specified for LaTeX output, this adds a
\label{}
command to enable Quarto's cross-referencing system.
Value
A table object formatted for the specified output:
For
format = "latex"
, a kableExtra-formatted LaTeX table with optional Quarto labelFor
format = "markdown"
, a markdown-formatted kable table with bold variable namesFor
format = "flextable"
, a flextable object optimized for Word output
Examples
if (FALSE) { # \dontrun{
# Flextable output for Word
flex_table <- margot_make_tables(
data = mydata,
vars = c("age", "gender", "income"),
by = "group",
labels = c("age" = "Age", "gender" = "Gender", "income" = "Income"),
factor_vars = "gender",
table1_opts = list(overall = FALSE, transpose = TRUE),
format = "flextable",
flex_opts = list(font_size = 8)
)
} # }