| table2docx | R Documentation |
Converts a data frame, data.table, or matrix to a fully editable Microsoft Word
document (.docx) using the flextable and officer packages.
Creates publication-ready tables with extensive formatting options including
typography, alignment, colors, and page layout. Tables can be further edited in
Microsoft Word after creation.
table2docx(
table,
file,
caption = NULL,
font_size = 8,
font_family = "Arial",
format_headers = TRUE,
bold_significant = TRUE,
bold_variables = FALSE,
p_threshold = 0.05,
indent_groups = FALSE,
condense_table = FALSE,
condense_quantitative = FALSE,
zebra_stripes = FALSE,
dark_header = FALSE,
paper = "letter",
orientation = "portrait",
width = NULL,
align = NULL,
return_ft = FALSE,
...
)
table |
Data frame, data.table, or matrix to export. Can be output from
|
file |
Character string specifying the output DOCX filename. Must have
|
caption |
Character string. Optional caption displayed above the table
in the Word document. Default is |
font_size |
Numeric. Base font size in points for table content. Default is 8. Typical range: 8-12 points. Headers use slightly larger size. |
font_family |
Character string. Font family name for the table. Must be
a font installed on the system. Default is |
format_headers |
Logical. If |
bold_significant |
Logical. If |
bold_variables |
Logical. If |
p_threshold |
Numeric. Threshold for bold p-value formatting. Only
used when |
indent_groups |
Logical. If |
condense_table |
Logical. If |
condense_quantitative |
Logical. If |
zebra_stripes |
Logical. If |
dark_header |
Logical. If |
paper |
Character string specifying paper size:
|
orientation |
Character string specifying page orientation:
|
width |
Numeric. Table width in inches. If |
align |
Character vector specifying column alignment for each column.
Options: |
return_ft |
Logical. If |
... |
Additional arguments passed to |
Package Requirements:
This function requires:
flextable - For creating formatted tables
officer - For Word document manipulation
Install if needed:
install.packages(c("flextable", "officer"))
Output Features:
The generated Word document contains:
Fully editable table (native Word table, not image)
Professional typography and spacing
Proper page setup (size, orientation, margins)
Caption (if provided) as separate paragraph above table
All formatting preserved but editable
Compatible with Word 2007 and later
Further Customization:
For programmatic customization beyond the built-in options, access the
flextable object:
Method 1: Via attribute (default)
result <- table2docx(table, "output.docx") ft <- attr(result, "flextable") # Customize flextable ft <- flextable::bold(ft, i = 1, j = 1, part = "body") ft <- flextable::color(ft, i = 2, j = 3, color = "red") # Re-save if needed doc <- officer::read_docx() doc <- flextable::body_add_flextable(doc, ft) print(doc, target = "customized.docx")
Method 2: Direct return
ft <- table2docx(table, "output.docx", return_ft = TRUE) # Customize immediately ft <- flextable::bg(ft, bg = "yellow", part = "header") ft <- flextable::autofit(ft) # Save to new document doc <- officer::read_docx() doc <- flextable::body_add_flextable(doc, ft) print(doc, target = "custom.docx")
Page Layout:
The function automatically sets up the Word document with:
Specified paper size and orientation
Standard margins (1 inch by default)
Continuous section (no page breaks before table)
Left-aligned table placement
For landscape orientation:
Automatically swaps page width and height
Applies landscape property to section
Useful for wide tables with many columns
Table Width Management:
Width behavior:
width = NULL - Auto-fits to content and page width
width = 6 - Exactly 6 inches wide
Width distributed evenly across columns by default
Can adjust individual column widths in Word after creation
For very wide tables:
Use orientation = "landscape"
Use paper = "legal" for extra width
Reduce font_size
Use condense_table = TRUE
Consider breaking across multiple tables
Typography:
The function applies professional typography:
Column headers: Bold, slightly larger font
Body text: Regular weight, specified font size
Numbers: Right-aligned for easy comparison
Text: Left-aligned for readability
Consistent spacing: Adequate padding in cells
Font family must be installed on the system where Word opens the document. Common cross-platform choices:
Arial - Sans-serif, highly readable
Times New Roman - Serif, traditional
Calibri - Microsoft default, modern
Helvetica - Sans-serif, professional
Zebra Striping:
When zebra_stripes = TRUE:
Alternating variables receive light gray background
All rows of same variable share same shading
Improves visual grouping
Particularly useful for tables with many factor variables
Color can be changed in Word after creation
Dark Header:
When dark_header = TRUE:
Header row: Dark gray/black background
Header text: White for high contrast
Modern, professional appearance
Draws attention to column names
Integration with R Markdown/Quarto:
For R Markdown/Quarto Word output:
# Create flextable for inline display ft <- table2docx(results, "temp.docx", return_ft = TRUE) # Display in R Markdown chunk ft # Renders in Word output
Or use flextable directly in chunks:
flextable::flextable(results)
Behavior depends on return_ft:
return_ft = FALSEInvisibly returns a list with components:
file - Path to created file
caption - Caption text (if provided)
The flextable object is accessible via attr(result, "flextable")
return_ft = TRUEDirectly returns the flextable object for immediate further customization
In both cases, creates a .docx file at the specified location.
autotable for automatic format detection,
table2pptx for PowerPoint slides,
table2pdf for PDF output,
table2html for HTML tables,
table2rtf for Rich Text Format,
table2tex for LaTeX output,
flextable for the underlying table object,
read_docx for Word document manipulation
Other export functions:
autotable(),
table2html(),
table2pdf(),
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
)
# Example 1: Basic Word export
if (requireNamespace("flextable", quietly = TRUE) &&
requireNamespace("officer", quietly = TRUE)) {
table2docx(results, file.path(tempdir(), "results.docx"))
}
old_width <- options(width = 180)
# Example 2: With caption
table2docx(results, file.path(tempdir(), "captioned.docx"),
caption = "Table 1: Multivariable Logistic Regression Results")
# Example 3: Landscape orientation for wide tables
table2docx(results, file.path(tempdir(), "wide.docx"),
orientation = "landscape")
# Example 4: Custom font and size
table2docx(results, file.path(tempdir(), "custom_font.docx"),
font_family = "Times New Roman",
font_size = 11)
# Example 5: Hierarchical display
table2docx(results, file.path(tempdir(), "indented.docx"),
indent_groups = TRUE)
# Example 6: Condensed table
table2docx(results, file.path(tempdir(), "condensed.docx"),
condense_table = TRUE)
# Example 7: With zebra stripes
table2docx(results, file.path(tempdir(), "striped.docx"),
zebra_stripes = TRUE)
# Example 8: Dark header style
table2docx(results, file.path(tempdir(), "dark.docx"),
dark_header = TRUE)
# Example 9: A4 paper for international journals
table2docx(results, file.path(tempdir(), "a4.docx"),
paper = "a4")
# Example 10: Get flextable for customization
result <- table2docx(results, file.path(tempdir(), "base.docx"))
ft <- attr(result, "flextable")
# Customize the flextable
ft <- flextable::bold(ft, i = 1, part = "body")
ft <- flextable::color(ft, j = "p-value", color = "blue")
# Example 11: Direct flextable return
ft <- table2docx(results, file.path(tempdir(), "direct.docx"), return_ft = TRUE)
ft <- flextable::bg(ft, bg = "yellow", part = "header")
# Example 12: Publication-ready table
table2docx(results, file.path(tempdir(), "publication.docx"),
caption = "Table 2: Adjusted Odds Ratios for Mortality",
font_family = "Times New Roman",
font_size = 10,
indent_groups = TRUE,
zebra_stripes = FALSE,
bold_significant = TRUE)
# Example 13: Custom column alignment
table2docx(results, file.path(tempdir(), "aligned.docx"),
align = c("left", "left", "center", "right", "right"))
# Example 14: Disable significance bolding
table2docx(results, file.path(tempdir(), "no_bold.docx"),
bold_significant = FALSE)
# Example 15: Stricter significance threshold
table2docx(results, file.path(tempdir(), "strict.docx"),
bold_significant = TRUE,
p_threshold = 0.01)
options(old_width)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.