在R标记中的for循环中创建多个Word文件报告
我正在尝试使用R标记自动生成多个报告。我有一个MS Word文件,我用在R标记中的for循环中创建多个Word文件报告,r,r-markdown,officer,R,R Markdown,Officer,我正在尝试使用R标记自动生成多个报告。我有一个MS Word文件,我用officer库导入到R。在这个MS Word文件中,我想用我在VarNames向量中定义的A、B和C名称替换单词alpha。然后,我想在一个单独的MS Word文件中为每个VarNames生成报告。我尝试使用下面的代码: library(officer) library(magrittr) library(rmarkdown) my_doc <- read_docx('Word_file.docx') varNam
officer
库导入到R。在这个MS Word文件中,我想用我在VarNames
向量中定义的A
、B
和C
名称替换单词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")
图书馆(官员)
图书馆(magrittr)
图书馆(rmarkdown)
我的文档好的,所以我认为最好的解决方案是:
# 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"
#记住使用setwd()相应地设置工作目录-所有读取
#和写入将在该目录中-或每次指定文件的路径,
#如果你喜欢那样的话。
#setwd(“xyz”)
图书馆(主任)
#我认为管道%>%非常有用,尤其是对于官员,因此:
图书馆(dplyr)
#为了使其成为一个完全可复制的示例,让我们创建一个Word文件
#其中只有“alpha”文本。
读取_docx()%>%
正文添加部分(“α”)%>%
打印(“Word_file.docx”)
#现在,让我们为循环创建要接受的向量
varNames%
#然后,根据varNames替换文本
正文替换所有文本(旧值=“alpha”,
new_value=varNames[i],
仅在光标处显示=FALSE,
ignore.case=FALSE)%>%
#然后,打印输出。应动态生成输出名称:
#每个报告(针对每个i)都需要有不同的名称。
打印(目标=粘贴0(“输出”,i,“.docx”))
}
#运行脚本后,工作目录中应包含4个文件:
#Word_file.docx“alpha”
#输出_1.docx“A”
#输出_2.docx“B”
#输出_3.docx“C”
您使用cursor\u backward()和docx\u show\u chunk()的全部内容似乎毫无意义。根据我的经验,最好不要过多使用光标功能
最佳实践可能是在模板中指定替换文本的特定位置(如您的示例和我的解决方案中所示),或者只是在R中动态构建整个文档(如果您想使用自定义样式,可以首先加载带有预定义样式的空模板)