R Knitr PDF: Is there a posssibility to automatically save PDF reports (generated from .Rmd) through a loop?

前端 未结 1 1964
天涯浪人
天涯浪人 2020-12-01 13:17

I would like to create a loop, which allows me to automatically save PDF reports, which were generated from a .Rmd file. For instance, if a variable \"ID\"

相关标签:
1条回答
  • 2020-12-01 13:29

    Adapting your example:

    You need one .rmd "template" file. 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 want, loop through the data subsets, and for each subset

    1. Define the subgroup object used inside the template
    2. render 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 produced 8 html files in my working directory, each with a summary of a different subset of the data.

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

    Rather than relying on global variables, another option would be to use parametrized reports, defining parameters in the YAML header, and passing the parameter values in as arguments to rmarkdown::render.

    0 讨论(0)
提交回复
热议问题