R – YAML current date in rmarkdown

knitrrr-markdownyaml

I'm wondering if there's a trick to put the current date in the YAML front-matter of a .rmd document to be processed by knitr and the rmarkdown package. I used to have the following line at the top of my wiki pages,

   _baptiste, `r format(Sys.time(), "%d %B, %Y")`_

and it would get converted to baptiste, 03 May, 2014 in the html output. Now, I would like to take advantage of the advanced pandoc wrapper provided by rmarkdown, but having r code in the YAML header doesn't seem to work:

---
title: "Sample Document"
output:
  html_document:
    toc: true
    theme: united
date: `r format(Sys.time(), "%d %B, %Y")`
author: baptiste
---

Error in yaml::yaml.load(front_matter) : 
  Scanner error: while scanning for the next token at line 6, column 7
 found character that cannot start any token at line 6, column 7
Calls: <Anonymous> ... output_format_from_yaml_front_matter -> 
       parse_yaml_front_matter -> <Anonymous> -> .Call

Any workaround?

Best Answer

This is a little bit tricky, but you just need to make the date field valid in YAML by quoting the inline R expression, e.g.

date: "`r format(Sys.time(), '%d %B, %Y')`"

Then the parsing error will be gone, and the date will be generated in the markdown output so Pandoc can use the value from Sys.time().

Related Topic