Search code examples
rgtsummarygt

Appending multiple gt_summary tables in same word doc


I am creating several gt_summary tables, one after the other. Is there a way to save the first in a word document, and then save each one in sequence, each time adding the new table into the same word document?

Here is an example code:

library(car) 
library(tidyverse)
library(gtsummary)

data(mtcars)

#creating first table
table1 <- mtcars %>%
gtsummary::tbl_summary(include = c(mpg,cyl,disp),
                       missing = "no",
                       statistic = list(
                         all_continuous() ~ "{mean} ({sd})",
                         all_categorical() ~ "{n} ({p}%)"),
                       digits = all_continuous() ~ 2,
                       label = mpg ~ "miles per gallon"
) 

table1

#saving table to docx file

table1 %>%
  as_gt()%>%
  gt::gtsave("table1.docx")

#creating second table
table2 <- mtcars %>%
  gtsummary::tbl_summary(include = c(wt,gear),
                         missing = "no",
                         statistic = list(
                           all_continuous() ~ "{mean} ({sd})",
                           all_categorical() ~ "{n} ({p}%)"),
                         digits = all_continuous() ~ 2
 ) 

table2

#saving table to same docx file as table 1

table2 %>%
  as_gt()%>%
  gt::gtsave("table1.docx")

I recieve the following error:

Unknown output format doc
Pandoc can convert to DOCX, but not to DOC.
Error: pandoc document conversion failed with error 22

Solution

  • This may not be ideal, but you can save your tables to individual Word documents and then use the officer package to "append". This would create a final document with all tables included.

    # Previously created table1.docx containing first table
    
    # Store second table as separate Word document
    table2 %>%
      as_gt()%>%
      gt::gtsave("table2.docx")
    
    library(officer)
    
    # Read in first table document as an R object
    doc1 <- read_docx("table1.docx")
    
    # Add content of second table docx to the object
    print(
      body_add_docx(doc1, src = "table2.docx", pos = "after"),
      target = "FinalTable.docx"
    )