4.2 Set the document title dynamically
You can use inline R code (see Section 3.1) anywhere in an Rmd document, including the YAML metadata section. This means some YAML metadata can be dynamically generated with inline R code, such as the document title. For example:
---
title: "An analysis of `r nrow(mtcars)` cars"
---
If your title depends on an R variable created later in the document, you may add the title
field in a later YAML section, e.g., the following:
---
author: "Smart Analyst"
output: pdf_document
---
I just tried really hard to calculate our market share:
```{r}
share <- runif(1)
```
---`r round(100 * share, 2)`% now!"
title: "Our market share is
---
`r if(share > 0.8) "happy" else "sad"` about it. I feel
In the example above, we added the document title after we created the variable share
. The title works in this case because Pandoc can read any number of YAML sections in a document (and merge them).
You can also generate titles or any YAML fields dynamically from parameters in parameterized reports (see Section 17.4), e.g.,
---
title: "`r params$doc_title`"
author: "Smart Analyst"
params:
doc_title: "The Default Title"
---
With the title being a dynamic parameter, you can easily generate a batch of reports with different titles.
We used the title as the example in this section, but the idea can be applied to any metadata fields in the YAML section.