Search code examples
rmergems-wordofficer

Writing word documents with the officer package: How to combine several rdocx objects?


I have several rdocx data objects created with the officer package in R. I want to combine these rdocx objects into only one rdocx object.

Consider the following example:

library("officer")

# Create two rdocx data objects
doc1 <- read_docx()
doc1 <- doc1 %>% 
  body_add_par("doc1_aaa", style = "Normal") %>% 
  body_add_par("doc1_bbb", style = "Normal") %>% 
  body_add_par("doc1_ccc", style = "Normal")

doc2 <- read_docx()
doc2 <- doc2 %>% 
  body_add_par("doc2_aaa", style = "Normal") %>% 
  body_add_par("doc2_bbb", style = "Normal") %>% 
  body_add_par("doc2_ccc", style = "Normal")

How could I merge these two rdocx objects so that the final output in Word looks as follows?

# Expected output
doc3 <- # combine doc1 and doc2
print(doc3, target = "Final-Output.docx")

# doc1_aaa
# doc1_bbb
# doc1_ccc
# doc2_aaa
# doc2_bbb
# doc2_ccc

Solution

  • You will need the function body_add_docx:

    library(officer)
    library(magrittr)
    
    
    doc2 <- read_docx()
    doc2 <- doc2 %>% 
      body_add_par("doc2_aaa", style = "Normal") %>% 
      body_add_par("doc2_bbb", style = "Normal") %>% 
      body_add_par("doc2_ccc", style = "Normal") %>% print(target = "doc2.docx")
    
    doc1 <- read_docx()
    doc1 <- doc1 %>% 
      body_add_par("doc1_aaa", style = "Normal") %>% 
      body_add_par("doc1_bbb", style = "Normal") %>% 
      body_add_par("doc1_ccc", style = "Normal") %>% 
      body_add_docx(src = "doc2.docx") %>% 
      print(target = "Final-Output.docx")