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

落爺英雄遲暮 提交于 2020-07-10 03:25:12

问题


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

回答1:


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")


来源:https://stackoverflow.com/questions/54704901/writing-word-documents-with-the-officer-package-how-to-combine-several-rdocx-ob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!