Setting document title in Rmarkdown from parameters

RR MarkdownPandoc

R Problem Overview


I've got an Rmarkdown template that works well, and I've parameterized it so I can generate variants of the same report from different data sources. However, I'd like to change the title of the report in each case. How do I do that?

Here's the YAML header I have so far:

---
title: "My Title"
author: "Me, Inc."
date: "August 4, 2015"
output: pdf_document
params:
  title: default
---

I've tried using params=list(title="ASDF") in the call to rmarkdown::render, and although my code can see that variable, it doesn't change the title. I've also tried using r params$title in the YAML, but that gives a syntax error.

Is there something else I should be trying? Thanks!

R Solutions


Solution 1 - R

Try to use a second YAML metadata block, and put the parameterized metadata in there.

I got the following code to work as expected (i.e., producing a document title from the list of params):

---
output: html_document
params: 
    set_title: "My Title!"
---

---
title: `r params$set_title`
---

The RMarkdown documentation notes that YAML metadata blocks are combined by Pandoc. Use the first block to define the parameter set, and the second one to use the parameters as metadata. Knitr will execute the R code to interpret the parameters in the second block.Then Pandoc will merge the metadata blocks together.

Update (2017):

This can be accomplished in a single block, like so:

---
output: html_document
params: 
    set_title: "My Title!"
title: "`r params$set_title`"
---

This works because the title comes after the params definition. I put quotes around the in-line R code to prevent "Scanner errors".

Solution 2 - R

This is a more simplified approach to the dynamic title challenge.

Decouple title from the top declaration like this:

From this:

---
title: "Sample Title"
output: pdf_document
---

To This:

---
output: pdf_document
--- 

```{r}
title_var <- "Sample Title"
```

---
title: `r title_var`
---

Within the R code chunks, declare title_var. Now the title is held within a variable. Hope this helps!

Solution 3 - R

Adding this answer as it helps in making R markdown titles dynamic.

Just use !r followed by the object name defined (test_title in the case below) to make the title dynamic.

---
output: pdf_document
params:
set_title: !r test_title
---
---
title: `r params$set_title`
---

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarlanView Question on Stackoverflow
Solution 1 - RTJ MahrView Answer on Stackoverflow
Solution 2 - RLahi SView Answer on Stackoverflow
Solution 3 - RRishabhView Answer on Stackoverflow