Setting document title in Rmarkdown from parameters

こ雲淡風輕ζ 提交于 2019-11-26 19:18:43

问题


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!


回答1:


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".




回答2:


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!




回答3:


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`
---


来源:https://stackoverflow.com/questions/31861569/setting-document-title-in-rmarkdown-from-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!