我想产生多个图形,并将它们保存在多个pdf文件基础上。基于某个类别,这些图表是不同的。使用此代码,它可以在生成1个pdf文件时工作
---
output: pdf_document
---
```{r setup, include=FALSE}
I <- "30-40“
套餐
库(Tidyverse)
库(Knitr)
库(Rmarkdown)
库(Tinytex)
库(Readxl)
库(data.table)
库(Lubridate)
创建随机数据
ID <- sample(seq(from = 1,to = 20,by = 1),100,replace = TRUE)
Date <- sample(seq(ymd("2019-01-01"),today(),by="day"),100,replace =TRUE
年龄<-样本(c(“20”,"20-30","30-40","40-50","50-60","60-70","70+"),
size = 100,
replace = TRUE,
prob=c(0.05, 0.1, 0.075, 0.15, 0.2, 0.175, 0.25))
Duration_call <-样本(序号(from= 30,to = 600,by = 5),100,replace = TRUE)
问题<-示例(c(“Question1”,"Question2","Question3","Question4"),100,replace = TRUE)
sample_data <- tibble(ID,日期,年龄,Duration_call,问题)
```{r}
KPI_3 <- sample_data %>%
filter(Age == i) %>%
mutate(Maand = lubridate::day(Date)) %>%
group_by(Maand, Question) %>%
summarize(Aantal_calls = n()) %>%
ggplot(aes(Maand, Aantal_calls, group = Question, color = Question)) +
geom_line()
但是,如果我使用这个脚本来遍历不同的类别(从而产生不同的pdf文件),它将无法工作。注意:在使用摘要统计信息(并将其缩进到rmd文件中)时,可以使用完全相同的代码。
## Packages
library(tidyverse)
library(knitr)
library(rmarkdown)
library(tinytex)
library(readxl)
library(data.table)
# Create random data
ID <- sample(seq(from = 1, to = 20, by = 1), 100, replace = TRUE)
Date <- sample(seq(ymd("2019-01-01"), today(), by="day"), 100, replace = TRUE)
Age <- sample(c("20", "20-30", "30-40", "40-50", "50-60", "60-70", "70+"),
size = 100,
replace = TRUE,
prob=c(0.05, 0.1, 0.075, 0.15, 0.2, 0.175, 0.25))
Duration_call <- sample(seq(from = 30, to = 600, by = 5), 100, replace = TRUE)
Question <- sample(c("Question1", "Question2", "Question3", "Question4"), 100, replace = TRUE)
sample_data <- tibble(ID, Date, Age, Duration_call, Question)
# For loop
for (i in unique(sample_data$Age)) {
print(i)
rmarkdown::render(input = "Child_script_1.Rmd", # must match RMD
output_format = "pdf_document",
output_file = paste("Age", i, ".pdf", sep=''),
output_dir = "MAP")
}
有人有什么建议吗?任何帮助都将不胜感激!
发布于 2019-10-02 14:25:27
如果我理解正确的话,您需要在您的markdown YAML文档中设置参数:
在本例中,它采用从输出创建的生成的图像(例如图形
---
title: "Title"
mainfont: Arial
output:
pdf_document:
latex_engine: xelatex
fig_caption: false
fig_height: 4
geometry: margin=.5in
params:
images_params: !r list.files(path = "./images/", pattern = "\\.jpg$", full.names = TRUE)
data: mtcars
---
在Markdown中,指定图像所在的位置
knitr::include_graphics(params$images_params) #calls on the param
并让另一个脚本运行它:
plotting_function <- function(df) {
split_df <- split(df, df$Question)
names <- names(split_df)
plots <- map2(split_df, names,
~ggplot(.x, aes(x = Age,
y = Duration_call)) +
geom_point()
)
}
reports <- plotting_function(sample_data)
reports %>% pwalk(rmarkdown::render,
input = "./path/Report.Rmd",
"pdf_document", envir = new.env())
这将创建一个新的pdf,并在您指定的位置插入图像。
我写了一些关于这个过程的here
https://stackoverflow.com/questions/58203042
复制