rpurrrflextableexport-to-wordofficer

Exporting all elements in column list using `officer`


I am working on a report for which I have to export a large number of similar data frames into nice looking tables in Word. I managed to the first bit by generating a column list of flextable objects using purrr (SO question for reference).

Now I would like to write all of the generated tables into a single word document, which for single flextable objects can be done using the following procedure:

library(tidyverse)
library(flextable)
library(officer)

# Basic data frame
df <- data.frame(school = c("A", "B", "A", "B", "A", "B"),
        students = c(round(runif(6, 1, 10), 0)),
        grade = c(1, 1, 2, 2, 3, 3))

# Generating column list containing flextable objects
list <- df %>% 
    group_by(school) %>%
    nest() %>% 
    mutate(ftables = map(data, flextable))

# Exporting single flextable object into Word
read_docx() %>% body_add_flextable(list$ftables[[2]]) %>% print("path")

I obviously want to avoid having to do this for all rows in ftables and, importantly, all tables should be written into the same Word document consecutively.

I toyed around with the purrr functions and writing loops, but the furthest I have come writes the tables into separate Word documents.


Solution

  • You can try

    my_doc <- read_docx()
    for(i in seq_along(list1$ftables)){
      my_doc <- body_add_flextable(my_doc,list1$ftables[[i]]) %>% 
        body_add_break() 
    }
    print(my_doc, target = "Doc.docx") %>% invisible()
    

    Tip, dont use function names to save objects. Thus, I renamed list to list1. The idea is to use a loop and save always to the same doc by adding a page break.

    Or try a purrr solution:

    # build a function to write a function
    write_word_table <- function(var, doc){
      doc %>%
        body_add_flextable(var) %>% 
        body_add_break() }
    
    my_doc <- read_docx()
    # use walk (the invisible function of map) to include all tables in one doc
    walk(list1$ftables, write_word_table, my_doc) 
    print(my_doc, target = "Doc1.docx") %>% invisible()