rr-markdown

Create a rmarkdown file and update parameters programatically


TLDR: I would like to create a rmarkdown file programatically based on a template, while populating the values of their parameters.

I know that rmarkdown::draft() can be used to "Create (and optionally edit) a draft of an R Markdown document based on a template."

I know that rmarkdown documents can have parameters (https://bookdown.org/yihui/rmarkdown/parameterized-reports.html).

I would like to programatically create an rmarkdown document based on a template while populating the values on their parameters, but draft() doesn't seem to allow that. Is this possible?

If not, would it be possible to make changes to the document (such as changing the title or some values?).


Solution

  • You should use draft() to create the document, and then use @JonSpring's suggestion to fill in parameter values when you render it.

    For example, your template could look like this:

    ---
    title: "`r params$title`"
    author: "Duncan Murdoch"
    date: "`r params$date`"
    output: html_document
    params: 
      title: "A default title"
      date: "Today"
      topic: "A default topic"
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    ## Introduction
    
    This is a document about `r params$topic`.
    

    When testing, you can use "knit with parameters" in RStudio, and you'll be prompted for entries for title, date and topic. In production, you can use

    rmarkdown::render("docname.Rmd", 
                      params=list(title = "The Title", 
                                  date = Sys.Date(), 
                                  topic = "Some topic")