本文介绍了用office包写word文档:如何组合多个rdocx对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 officer 包创建了多个 rdocx 数据对象 在 R 中.我想将这些 rdocx 对象合并为一个 rdocx 对象.

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.

考虑以下示例:

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

如何合并这两个 rdocx 对象,使 Word 中的最终输出如下所示?

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

推荐答案

您将需要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")

这篇关于用office包写word文档:如何组合多个rdocx对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-31 18:47