If you are looking for something which perhaps is most in keeping with the R Markdown workflow, you can customise the template which is used to build the LaTeX output and add all the extra LaTeX code directly to this.
1. Copying Template
Firstly, we must make a copy of the template used by R Markdown. The following code will create this in your current working directory:
file.copy(system.file("rmd/latex/default-1.17.0.2.tex",
package = "rmarkdown"), "template.tex")
2. Adding Variables
With our copy, we can define our own pandoc variables which will be inserted into the output document. This allows us to specify parameters in the YAML section of the document and they will be updated in the output format. It is exactly the same mechanism which allows us to add title
, author
, date
and for them to be added to the output format.
I have added some code to the front matter of the document at lines 253-255. The exact location doesn't matter, but I also tend to put my customisations before the \begin{document}
argument:
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[LO, LE]{$params.value$}
\fancyhead[RO, RE]{$yourParam$}
3. Calling Template from R Markdown
We can reference the custom template to our R Markdown document as explained here. Here is my minimal example:
---
output:
pdf_document:
template: template.tex
params:
value: Text
yourParam: "`r Sys.Date()`"
---
`r params$value`
The two parameters will be added to the output replacing the $params.value$
and $yourParam$
, and result in the output below:

The example highlights how the YAML parameters don't have to be nested within the params
argument, as specified in your original question. Having them specified within the parameters mainly has benefits if you want to build a parameterized report
Note: the approach of replacing variables using the pandoc notation $variable$
is only possible for the main template file defined under the template
option. It won't work for any of the includes
arguments or any other external LaTeX files. See here for more details.
\include
, but if I wanted to use in in the preamble (in header)...include>in_header
(> 100 lines of code) in the original markdown document.