I want to produce multiple graphs and save them on multiple pdf files based. These graphs are different based on a certain category. With this code, it works when producing 1 pdf file
---
output: pdf_document
---
```{r setup, include=FALSE}
i <- "30-40"
## Packages
library(tidyverse)
library(knitr)
library(rmarkdown)
library(tinytex)
library(readxl)
library(data.table)
library(lubridate)
# 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)
```
```{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()
```
However, if I use this script in order to loop over the different categories (and thus produce different pdf files), it won't work. Note: when using summary statistics (and indenting them into the rmd file), the exact code does work.
## 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")
}
Does someone have any suggestions? Any help would be much appreciated!