Based on the previous solution, Does the gtsummary package have a function that allows the exported table to include footnotes on every page?
I successfully implemented pagination for the RTF output, meaning that titles and footnotes can be repeated on each page. However, during this process, I had some thoughts and encountered a few issues that need to be addressed:
Manual adjustment of page size and rows: This requires adjusting based on the actual output. Otherwise, if the page is too long, objects that should appear on the next page might appear on the previous page. Is there a way to intelligently ensure that split objects are presented on a new page, rather than requiring manual adjustments?
Inconsistent widths across pages: After splitting into different objects, the width of the objects on each page seems to vary. Is there a simple way to control this?
library(dplyr)
library(gtsummary)
library(flextable)
# Load example datasets
adsl <- pharmaverseadam::adsl
adae <- pharmaverseadam::adae
# Pre-processing --------------------------------------------
adae <- adae %>%
dplyr::filter(
# safety population
SAFFL == "Y"
)
# Create hierarchical table
tbl <- adae |>
tbl_hierarchical(
variables = c(AESOC, AEDECOD),
by = ARM,
id = USUBJID,
denominator = adsl,
overall_row = TRUE,
label = "..ard_hierarchical_overall.." ~ "Any Adverse Events"
)
# Split the table into smaller chunks
tbl_split <- tbl_split_by_rows(tbl, row_numbers = seq(10, nrow(tbl), by = 10))
# Convert each split table into a flextable
flextables <- lapply(seq_along(tbl_split), function(i) {
tbl_split[[i]] |>
as_flex_table() |>
add_header_lines(as_paragraph(as_chunk(
paste0("Table 15.3: 1 AE by SOC/PT"),
props = fp_text_default(font.family = "San Serif",
font.size = 12))
)) |>
autofit()|>
paginate(init = TRUE, hdr_ftr = TRUE) # Ensure pagination is initialized
})
# Combine all flextables into a named list
flextable_list <- setNames(flextables, paste0("Page_", seq_along(flextables)))
flextable_list<-flextables
# Define section properties for RTF formatting (with page breaks)
sect_properties <- officer::prop_section(
page_size = officer::page_size(orient = "landscape", width = 20, height = 8),
page_margins = officer::page_mar(top = 1, bottom = 1, left = 1, right = 1),
type = "nextPage" # Ensures page breaks between sections
)
# Save each flextable with explicit page breaks
do.call(
flextable::save_as_rtf,
c(flextable_list, list(path = "tbl.rtf", pr_section = sect_properties))
)
This is a great question, and something I hadn't considered previsouly. In your code, if you swap flextable::autfit() and instead specify the column widths with flextable:width() that will force all the tables to have a common width in the results.
FYI We started a small package for printing paginated tables to docx. It's still a work in progress https://insightsengineering.github.io/pager/