Alberto Stefanelli
Alberto Stefanelli

Reputation: 320

Parameterize both Author and Title in Markdown using a loop

I need to parameterize both the title and the author of a Markdown report. I am able to set the title and generate reports from a loop that subset my dataset but I can't figure out how to match the title with a corresponding author that I've in my dataset.

For instance, I've a set of courses taught by different instructors. I can get the title of the course as the title of the markdown report:

for (c in unique((na.omit(data$NAME_OF_THE_COURSE)))){
 rmarkdown::render('LOCATION_WHATEVER',
                   params = list(set_title= c),
                   output_file =  paste("report_post_", c, '_', Sys.Date(), ".html", sep=''), 
                   output_dir = 'LOCATION_WHATEVER')
}

But I am not able to set the author since I would need another loop where

for (author in unique((na.omit(data$NAME_OF_INSTRUCTUR)))) 

Any suggestion?

Upvotes: 2

Views: 1564

Answers (1)

camille
camille

Reputation: 16862

I almost always avoid for loops, since one of the beauties of R is that you can work over vectors. Instead, I'd use an apply family function from base R or, my preference, a map family function from purrr/tidyverse.

You can do this a few ways, but I went with a nested list. It's a list of course info, where each course is a list of the professor's name and the class name. Using walk, you map over the outer list, take the names from each class, and use those as parameters for render.

Here's the dummy Rmarkdown, with the filename dummy_rmd.Rmd:

Edit: You can use inline R code inside your yaml to set the title and author of the document, as explained in this answer. The items with the inline code need to be after params, so there's something defined already.

---
output: html_document
params:
  prof: "Person 1"
  class: "Class A"
title: "`r params$class`"
author: "`r params$prof`"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
prof <- params$prof
class <- params$class

plot(1:5, runif(5), main = sprintf("Plot for %s taught by %s", class, prof))
```

Then in a script in the same directory:

class_list <- list(
    list(prof = "Person 1", class = "Class A"),
    list(prof = "Person 2", class = "Class B"),
    list(prof = "Person 3", class = "Class C")
)

purrr::walk(class_list, function(class_info) {
    prof <- class_info$prof
    class <- class_info$class
    rmarkdown::render(
        input = "dummy_rmd.Rmd", 
        output_file = sprintf("output_%s_%s.html", prof, class),
        params = list(prof = prof, class = class)
        )
})

This gives me html files, one for each course, named accordingly. HTML output looks like:

enter image description here

Upvotes: 4

Related Questions