使用下面的代码,我能够为mtcars数据集的子集生成一个ppt报告:
library(ggplot2)
library(tidyverse)
library(patchwork)
library(officer)
library(officedown)
library(glue)
small <- mtcars %>%
filter(carb %in% c(1, 2))
p1 <- ggplot(mpg, wt, data = small, colour = cyl)
p2 <- ggplot(mpg, data = small) + ggtitle("small")
p <- p1 | p2
template_pptx <- read_pptx()
report <- add_slide(template_pptx, layout = "Title and Content", master = "Office Theme") %>%
ph_with(value=p, location = ph_location_label(ph_label = "Content Placeholder 2"))
print(report, target=glue('report for small car.pptx'))现在,假设我们还需要为以下数据集复制报表生成过程:
middle <- mtcars %>%
filter(carb %in% c(3, 4))
large <- mtcars %>%
filter(carb %in% c(6, 8))我的想法是将多个ggplots部分转换为一个函数并保存到脚本plot.R中,然后编写名为main.R的伪代码脚本来运行整个过程,并分别为小、中、大型数据集生成3份报告:
# main.R
for i in c(small, middle, large){
source('plot.R')
# maybe need to import and run plot function() from plot.R
# save figure to ppt
template_pptx <- read_pptx("./ppt_template.pptx")
report <- add_slide(template_pptx, layout = "Title and Content", master = "Office Theme") %>%
ph_with(value=p, location = ph_location_label(ph_label = "Content Placeholder 2"))
print(report, target=glue('report for {i} car.pptx'))
}我遇到的问题是,我不知道如何将绘图代码转换为函数并传递params (可能会保存一个config.yaml文件,以防出现多个params?)到预定义函数,并最终生成参数化报告?
非常感谢您的意见和帮助,提前。
参考资料:
R: multiple ggplot2 plot using d*ply
https://cran.r-project.org/web/packages/egg/vignettes/Ecosystem.html
R - How to generate parameterized reports via nested tibbles + pwalk(rmarkdown::render)
发布于 2022-01-11 16:46:42
您可以将绘图代码放入一个函数中,例如,使用两个参数,一个dataframe (x)和一个title。
类似地,将代码放在函数中准备pptx,例如接受两个参数,一个dataframe (x)和一个标题或文件名,或者.
在下面的代码中,我将三个数据集放在一个列表中,然后使用purrr::iwalk循环这个列表,为每个数据集创建一个pptx报告。使用purrr::iwalk,将数据集的名称作为第二个参数传递给报告函数。
library(ggplot2)
library(patchwork)
library(dplyr)
library(purrr)
library(officer)
library(glue)
plot_fun <- function(x, title) {
p1 <- ggplot(data = x, aes(mpg, wt, colour = cyl))
p2 <- ggplot(data = x, aes(mpg)) + ggtitle(title)
p1 | p2
}
pptx_fun <- function(x, y) {
p <- plot_fun(x, title = y)
template_pptx <- read_pptx()
report <- add_slide(template_pptx, layout = "Title and Content", master = "Office Theme") %>%
ph_with(value = p, location = ph_location_label(ph_label = "Content Placeholder 2"))
print(report, target=glue('report for {y} car.pptx'))
}
data_list <- lapply(list(small = 1:2, medium = 3:4, large = 5:6), function(x) filter(mtcars, carb %in% x))
purrr::iwalk(data_list, pptx_fun)https://stackoverflow.com/questions/70670231
复制相似问题