| table2pdf | R Documentation |
Converts a data frame, data.table, or matrix to a professionally formatted PDF document using LaTeX as an intermediate format. Provides extensive control over page layout, typography, and formatting for publication-ready output. Particularly well-suited for tables from regression analyses, descriptive statistics, and model comparisons. Requires xtable for export.
table2pdf(
table,
file,
orientation = "portrait",
paper = "letter",
margins = NULL,
fit_to_page = TRUE,
font_size = 8,
caption = NULL,
caption_size = NULL,
format_headers = TRUE,
variable_padding = FALSE,
cell_padding = "normal",
bold_significant = TRUE,
bold_variables = FALSE,
p_threshold = 0.05,
align = NULL,
indent_groups = FALSE,
condense_table = FALSE,
condense_quantitative = FALSE,
zebra_stripes = FALSE,
stripe_color = "gray!20",
dark_header = FALSE,
show_logs = FALSE,
...
)
table |
Data frame, data.table, or matrix to export. Can be output from
|
file |
Character string specifying the output PDF filename. Must have
|
orientation |
Character string specifying page orientation:
|
paper |
Character string specifying paper size:
|
margins |
Numeric vector of length 4 specifying margins in inches as
|
fit_to_page |
Logical. If |
font_size |
Numeric. Base font size in points. Default is 8. Smaller values accommodate more content; larger values improve readability. Typical range: 6-12 points. |
caption |
Character string. Optional caption displayed below the table.
Supports LaTeX formatting for multi-line captions, superscripts, italics, etc.
See Details for formatting guidance. Default is |
caption_size |
Numeric. Caption font size in points. If |
format_headers |
Logical. If |
variable_padding |
Logical. If |
cell_padding |
Character string or numeric specifying vertical padding within table cells:
Adjusts |
bold_significant |
Logical. If |
bold_variables |
Logical. If |
p_threshold |
Numeric. Threshold for bold p-value formatting. Only
used when |
align |
Character string or vector specifying column alignment. Options:
If |
indent_groups |
Logical. If |
condense_table |
Logical. If
Significantly reduces table height. Default is |
condense_quantitative |
Logical. If |
zebra_stripes |
Logical. If |
stripe_color |
Character string. LaTeX color specification for zebra
stripes. Default is |
dark_header |
Logical. If |
show_logs |
Logical. If |
... |
Additional arguments passed to |
LaTeX Requirements:
This function requires a working LaTeX installation. The function checks for LaTeX availability and provides installation guidance if missing.
Recommended LaTeX distributions:
TinyTeX (lightweight, R-integrated): Install via
tinytex::install_tinytex()
TeX Live (comprehensive, cross-platform)
MiKTeX (Windows)
MacTeX (macOS)
Required LaTeX packages (auto-installed with most distributions):
fontenc, inputenc - Character encoding
array, booktabs, longtable - Table formatting
graphicx - Scaling tables
geometry - Page layout
pdflscape, lscape - Landscape orientation
helvet - Sans-serif fonts
standalone, varwidth - Auto-sizing (for paper = "auto")
float, caption - Floats and captions
xcolor, colortable - Colors (for zebra_stripes or dark_header)
Caption Formatting:
Captions support LaTeX commands for rich formatting:
# Multi-line caption with line breaks
caption = "Table 1: Multivariable Analysis\\
OR = odds ratio; CI = confidence interval"
# With superscripts (using LaTeX syntax)
caption = "Table 1: Results\\
Adjusted for age and sex\\
p-values from Wald tests"
# With special characters (must escape percent signs)
caption = "Results for income (in thousands)"
Auto-Sizing (paper = "auto"):
When paper = "auto", the function attempts to create a minimal PDF
sized exactly to the table content:
Using the standalone LaTeX class (cleanest output)
Fallback to pdfcrop utility if standalone unavailable
Fallback to minimal margins if neither available
Table Width Management:
For wide tables that don't fit on the page:
Use orientation = "landscape"
Use fit_to_page = TRUE (default) to auto-scale
Reduce font_size (e.g., 7 or 6)
Consider paper = "auto" for maximum flexibility
Troubleshooting:
If PDF compilation fails:
Check that LaTeX is installed: Run Sys.which("pdflatex")
Set show_logs = TRUE and examine the .log file
Common issues:
Missing LaTeX packages: Install via package manager
Special characters in text: Escape properly
Very wide tables: Use landscape or reduce font size
Caption formatting: Check LaTeX syntax
Invisibly returns NULL. Creates a PDF file at the specified
location. If compilation fails, check the .log file (if
show_logs = TRUE) for error details.
autotable for automatic format detection,
table2tex for LaTeX source files,
table2html for HTML output,
table2docx for Microsoft Word,
table2pptx for PowerPoint,
table2rtf for Rich Text Format,
desctable for descriptive tables,
fit for regression tables
Other export functions:
autotable(),
table2docx(),
table2html(),
table2pptx(),
table2rtf(),
table2tex()
data(clintrial)
data(clintrial_labels)
# Create example table
results <- fit(
data = clintrial,
outcome = "os_status",
predictors = c("age", "sex", "treatment", "stage"),
labels = clintrial_labels
)
# Test that LaTeX can compile (needed for all PDF examples)
has_latex <- local({
if (!nzchar(Sys.which("pdflatex"))) return(FALSE)
test_tex <- file.path(tempdir(), "summata_latex_test.tex")
writeLines(c("\\documentclass{article}", "\\usepackage{booktabs}",
"\\begin{document}", "test", "\\end{document}"), test_tex)
tryCatch(
system2("pdflatex", c("-interaction=nonstopmode",
paste0("-output-directory=", tempdir()), test_tex),
stdout = FALSE, stderr = FALSE),
error = function(e) 1L) == 0L
})
# Example 1: Basic PDF export
if(has_latex){
table2pdf(results, file.path(tempdir(), "basic_results.pdf"))
}
if(has_latex){
# Example 2: Landscape orientation for wide tables
table2pdf(results, file.path(tempdir(), "wide_results.pdf"),
orientation = "landscape")
# Example 3: With caption
table2pdf(results, file.path(tempdir(), "captioned.pdf"),
caption = "Table 1: Multivariable logistic regression results")
# Example 4: Multi-line caption with formatting
table2pdf(results, file.path(tempdir(), "formatted_caption.pdf"),
caption = "Table 1: Risk Factors for Mortality\\\\
aOR = adjusted odds ratio; CI = confidence interval")
# Example 5: Auto-sized PDF (no fixed page dimensions)
table2pdf(results, file.path(tempdir(), "autosize.pdf"),
paper = "auto")
# Example 6: A4 paper with custom margins
table2pdf(results, file.path(tempdir(), "a4_custom.pdf"),
paper = "a4",
margins = c(0.75, 0.75, 0.75, 0.75))
# Example 7: Larger font for readability
table2pdf(results, file.path(tempdir(), "large_font.pdf"),
font_size = 11)
# Example 8: Indented hierarchical display
table2pdf(results, file.path(tempdir(), "indented.pdf"),
indent_groups = TRUE)
# Example 9: Condensed table (reduced height)
table2pdf(results, file.path(tempdir(), "condensed.pdf"),
condense_table = TRUE)
# Example 10: With zebra stripes
table2pdf(results, file.path(tempdir(), "striped.pdf"),
zebra_stripes = TRUE,
stripe_color = "gray!15")
# Example 11: Dark header style
table2pdf(results, file.path(tempdir(), "dark_header.pdf"),
dark_header = TRUE)
# Example 12: Combination of formatting options
table2pdf(results, file.path(tempdir(), "publication_ready.pdf"),
orientation = "portrait",
paper = "letter",
font_size = 9,
caption = "Table 2: Multivariable Analysis\\\\
Model adjusted for age, sex, and clinical factors",
indent_groups = TRUE,
zebra_stripes = TRUE,
bold_significant = TRUE,
p_threshold = 0.05)
# Example 13: Adjust cell padding
table2pdf(results, file.path(tempdir(), "relaxed_padding.pdf"),
cell_padding = "relaxed") # More spacious
# Example 14: No scaling (natural table width)
table2pdf(results, file.path(tempdir(), "no_scale.pdf"),
fit_to_page = FALSE,
font_size = 10)
# Example 15: Hide significance bolding
table2pdf(results, file.path(tempdir(), "no_bold.pdf"),
bold_significant = FALSE)
# Example 16: Custom column alignment
table2pdf(results, file.path(tempdir(), "custom_align.pdf"),
align = c("c", "c", "c", "c", "c", "c", "c"))
# Example 17: Descriptive statistics table
desc_table <- desctable(clintrial, by = "treatment",
variables = c("age", "sex", "bmi", "stage"), labels = clintrial_labels)
table2pdf(desc_table, file.path(tempdir(), "descriptive.pdf"),
caption = "Table 1: Baseline Characteristics by Treatment Group",
orientation = "landscape")
# Example 18: Model comparison table
models <- list(
base = c("age", "sex"),
full = c("age", "sex", "bmi", "treatment")
)
comparison <- compfit(
data = clintrial,
outcome = "os_status",
model_list = models
)
table2pdf(comparison, file.path(tempdir(), "model_comparison.pdf"),
caption = "Table 3: Model Comparison Statistics")
# Example 19: Very wide table with aggressive fitting
wide_model <- fit(
data = clintrial,
outcome = "os_status",
predictors = c("age", "sex", "race", "bmi", "smoking",
"hypertension", "diabetes", "treatment", "stage")
)
table2pdf(wide_model, file.path(tempdir(), "very_wide.pdf"),
orientation = "landscape",
font_size = 7,
fit_to_page = TRUE,
condense_table = TRUE)
# Example 20: With caption size control
table2pdf(results, file.path(tempdir(), "caption_size.pdf"),
font_size = 8,
caption_size = 6,
caption = "Table 4: Results with Compact Caption\\\\
Smaller caption fits better on constrained pages")
# Example 21: Troubleshooting - keep logs
table2pdf(results, file.path(tempdir(), "debug.pdf"),
show_logs = TRUE)
# If it fails, check debug.log for error messages
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.