Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting document title in Rmarkdown from parameters

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!

like image 286
Harlan Avatar asked Aug 06 '15 16:08

Harlan


People also ask

How do you set a title in R Markdown?

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

How do I use parameters in R Markdown?

Parameters in an R Markdown document are very simple to use. In the yaml header (the section at the top of the markdown document), you just have to add a couple new lines for your parameters to hardcode them in. Once they're coded in, they will be available in the params object for use in the rest of the analysis.

How do I change a document in R Markdown?

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want. When you click the button, rmarkdown will duplicate your text in the new file format.


1 Answers

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

like image 129
TJ Mahr Avatar answered Oct 12 '22 04:10

TJ Mahr