R Knitr PDF: Is it possible to automatically save PDF reports (created from .Rmd) through a loop?

I would like to create a loop that allows me to automatically save PDF reports that were generated from a .Rmd file. For example, if the variable "ID" has 10 lines, I would like R to automatically save 10 reports in a specific directory. These reports depend on the identifier selected.

A previous post ( Using loops with knitr to create multiple reports in PDF format ... need a little help to get me behind the hump ) discussed the creation of several PDF reports created from .Rnw files. I tried to apply the approach as follows:

#Data ```{r, include=FALSE} set.seed(500) Score <- rnorm(40, 100, 15) Criteria1<-rnorm(40, 10, 5) Criteria2<-rnorm(40, 20, 5) ID <- sample(1:1000,8,replace=T) df <- data.frame(ID,Score,Criteria1,Criteria2) #instead of manually choosing the ID: subgroup<- subset(df, ID==1) # I would like to subset the Data through a loop. My approach was like like this: for (id in unique(df$ID)){ subgroup<- df[df$ID == id,]} ``` ```{r, echo=FALSE} #Report Analysis summary(subgroup) ``` #Here will be some text about the summary. # At the end the goal is to produce automatic pdf reports with the ID name as a filename: library("rmarkdown") render("Automated_Report.rmd",output_file = paste('report.', id, '.pdf', sep='')) 
+7
dynamic r pdf knitr report
source share
1 answer

Adapting your example:

You need one .rmd "template" template. It could be something like this, save it as template.rmd .

 This is a subgroup report. ```{r, echo=FALSE} #Report Analysis summary(subgroup) ``` 

Then you need an R script that will load the data you need, iterate over subsets of data and for each subset

  • Define the subgroup object used inside the template
  • map the template to the desired output

So, in this separate script:

 # load data set.seed(500) Score <- rnorm(40, 100, 15) Criteria1<-rnorm(40, 10, 5) Criteria2<-rnorm(40, 20, 5) ID <- sample(1:1000,8,replace=T) df <- data.frame(ID,Score,Criteria1,Criteria2) library("rmarkdown") # in a single for loop # 1. define subgroup # 2. render output for (id in unique(df$ID)){ subgroup <- df[df$ID == id,] render("template.rmd",output_file = paste0('report.', id, '.html')) } 

This created 8 html files in my working directory, each of which contains a summary of another subset of the data.

Please note that this will not work if you try to click the knit button inside RStudio, as this will run the R code in a separate R session. However, when explicitly starting from the console using render (or knit2pdf ), the R code in the rmd file is all still has access to the global environment.

Another option to achieve this is to use the brew package.

+9
source share

All Articles