【问题标题】:Creating multiple Word file reports in a for loop in R Markdown在 R Markdown 的 for 循环中创建多个 Word 文件报告
【发布时间】:2021-01-27 21:06:48
【问题描述】:

我正在尝试使用 R markdown 自动生成多个报告。我有一个 MS Word 文件,我使用 officer 库导入到 R 中。在这个 MS Word 文件中,我想用我在 VarNames 向量中定义的 ABC 名称替换单词 alpha。然后,我想在单独的 MS Word 文件中为每个 VarNames 生成报告。我尝试使用下面的代码:

library(officer)
library(magrittr)
library(rmarkdown)

my_doc <- read_docx('Word_file.docx')

varNames <- c("A", "B", "C")


for (i in 1:length(varNames)) {
doc2 <- body_replace_all_text(my_doc, old_value = "alpha",new_value = varNames[i], only_at_cursor=FALSE,ignore.case =FALSE);
}
doc2 <- cursor_backward(doc2)
docx_show_chunk(doc2)
my_doc2 <- print(doc2, target ="/Users/majerus/Desktop/R/auto_reporting/my_doc2.docx")

但代码只为变量名A 生成一份报告。你能帮我弄清楚代码有什么问题吗?即使我可以生成 .pdf 或 .html 格式的报告也可以。谢谢!

【问题讨论】:

    标签: r r-markdown officer


    【解决方案1】:

    好的,所以我认为最好的解决方案是:

    # Remember to set your working directory with setwd() accordingly - all reads 
    # and writes will be in that dir - or specify the path to the file every time, 
    # if you prefer it that way.
    
    # setwd("xyz")
    
    library(officer)
    
    # I think the pipes %>% are very useful, ESPECIALLY with officer, so:
    library(dplyr)
    
    
    # To make it a fully reproductive example, let's create a Word file 
    # with only "alpha" text in it.
    
    read_docx() %>%
      body_add_par("alpha") %>%
      print("Word_file.docx")
    
    # now, let's create the vector for the loop to take in
    
    varNames <- c("A", "B", "C")
    
    
    ### Whole docx creation script should be inside the for loop
    
    for (i in 1:length(varNames)) {
      
      #firsty, read the file
      read_docx("Word_file.docx") %>% 
        
        #then, replace the text according to varNames
        body_replace_all_text(old_value = "alpha",
                              new_value = varNames[i], 
                              only_at_cursor=FALSE,
                              ignore.case =FALSE) %>%
        
        # then, print the outputs. Output name should be generated dynamically:
        # every report (for every i) need to have a different name.
        print(target = paste0("Output_",i,".docx")) 
    
    }
    
    # After running your script, in your working directory should be 4 files:
    # Word_file.docx "alpha"
    # Output_1.docx "A"
    # Output_2.docx "B"
    # Output_3.docx "C"
    
    

    您使用 cursor_backward() 和 docx_show_chunk() 的全部内容似乎毫无意义。根据我的经验 - 最好不要过多地使用光标功能。

    最佳实践可能是在模板中指定替换文本的特定位置(如在您的示例和我的解决方案中) - 或者只是在 R 中动态构建整个文档(您可以首先加载具有预定义样式的空模板,如果你想使用自定义的)。

    【讨论】:

      猜你喜欢
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      相关资源
      最近更新 更多