使用下面的代碼,我可以為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'))
}
我遇到的問題是我不知道如何將繪圖代碼轉換為函式并將引數(也許保存config.yaml檔案以防我們有很多引數?)傳遞給預定義函式,最后生成引數化報告?
非常感謝您的評論和提前幫助。
參考:
R:使用 d*ply 的多個 ggplot2 繪圖
https://cran.r-project.org/web/packages/egg/vignettes/Ecosystem.html
R - 如何通過嵌套 tibbles pwalk(rmarkdown::render) 生成引數化報告
uj5u.com熱心網友回復:
您可以將您的繪圖代碼放在一個函式中,例如,該函式需要兩個引數,一個資料框 (x) 和一個標題。
同樣,將準備 pptx 的代碼放入一個函式中,例如,該函式接受兩個引數,一個資料框 (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://www.uj5u.com/yidong/409167.html
標籤:
上一篇:你可以在R中結合case_when和startsWith來進行復雜的分組嗎
下一篇:從繪圖圖表的第th條中洗掉文本
