rgtsummaryofficerr-flextable

How to make the title of a gtsummary object correctly paginated and left-aligned when exporting using officer/flextable?


I have two main questions here. The first is how to control the alignment of the title specified in modify_caption so that it is displayed left-aligned when exporting to RTF using flextable/officer. The second is how to ensure that the content of modify_caption and modify_source_note is repeated on every page after pagination, rather than only appearing at the beginning and end. The current code and output are shown below.


# Load libraries & data -------------------------------------
library(dplyr)
library(gtsummary)
library(officer)
library(flextable)
library(pharmaverseadam)

adsl<-pharmaverseadam::adsl
adae<-pharmaverseadam::adae

# Pre-processing --------------------------------------------

adae <- adae %>%
  dplyr::filter(
    # safety population
    SAFFL == "Y"
  )

tbl <- adae |>
  tbl_hierarchical(
    variables = c(AESOC, AEDECOD),
    by = ARM,
    id = USUBJID,
    denominator = adsl,
    overall_row = TRUE,
    label = "..ard_hierarchical_overall.." ~ "Any Adverse Events"
  )%>%
  modify_caption("Table 15.3: 1 AE by SOC/PT")%>%
  modify_source_note("xxxx is defined as xxxx.")
tbl

tbl <- tbl%>%
  as_flex_table()

tbl[1]
tbl[2]


dim(tbl)
sect_properties <- prop_section(
  type = "nextPage",
  page_size = page_size(
    orient = "landscape",
    width = 12, height = 11.7
  ),
  #section_columns = section_columns(widths = c(4.75, 4.75)),
  page_margins = page_mar()
)

save_as_rtf(tbl, path = 'tbl.rtf',pr_section = sect_properties)

enter image description here


Solution

  • Instead of gtsummary::modify_caption(), use flextable::set_caption() after converting to flextable (with as_flextable()):

    tbl |>
      set_caption("Table 15.3: 1 AE by SOC/PT", 
                  style = "Table Caption", 
                  align_with_table = FALSE)
    

    However, since you want it to be repeated on every page, I'd use headers with add_header_lines (would modify to look like the caption) instead of caption;

    adae |>
      tbl_hierarchical(
        variables = c(AESOC, AEDECOD),
        by = ARM,
        id = USUBJID,
        denominator = adsl,
        overall_row = TRUE,
        label = "..ard_hierarchical_overall.." ~ "Any Adverse Events"
      ) |>
      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))
        )) |>
      add_footer_lines("xxxx is defined as xxxx.") |>
      align(part = "header", align = "left") |>
      align(part = "footer", align = "left") |>
      hline_top(part = "header", 
                border = officer::fp_border(width = 0)) |>
      autofit() -> tbl_clean
    
    save_as_rtf(tbl_clean, path = 'tbl.rtf',pr_section = sect_properties)