首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用军官生成参数化ppt报告

使用军官生成参数化ppt报告
EN

Stack Overflow用户
提问于 2022-01-11 16:33:03
回答 1查看 76关注 0票数 0

使用下面的代码,我能够为mtcars数据集的子集生成一个ppt报告:

代码语言:javascript
复制
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'))

现在,假设我们还需要为以下数据集复制报表生成过程:

代码语言:javascript
复制
middle <- mtcars %>% 
  filter(carb %in% c(3, 4))

large <- mtcars %>% 
  filter(carb %in% c(6, 8))

我的想法是将多个ggplots部分转换为一个函数并保存到脚本plot.R中,然后编写名为main.R的伪代码脚本来运行整个过程,并分别为小、中、大型数据集生成3份报告:

代码语言:javascript
复制
# 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)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-11 16:46:42

您可以将绘图代码放入一个函数中,例如,使用两个参数,一个dataframe (x)和一个title。

类似地,将代码放在函数中准备pptx,例如接受两个参数,一个dataframe (x)和一个标题或文件名,或者.

在下面的代码中,我将三个数据集放在一个列表中,然后使用purrr::iwalk循环这个列表,为每个数据集创建一个pptx报告。使用purrr::iwalk,将数据集的名称作为第二个参数传递给报告函数。

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70670231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档