YAML current date in rmarkdown
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()
.
Just following up on @Yihui. Oddly, I have found that:
'`r format(Sys.Date(), "%B %d, %Y")`'
works better than:
"`r format(Sys.Date(), '%B %d, %Y')`"
For the latter RStudio chooses to change the outer quotes to '
whenever switching between HTML and PDF output and thus breaking the code.
Or just single quote the double quotes and vice versa, This works well.
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
date: '`r format(Sys.time(), "%d %B, %Y")`'
author: baptiste
---
One workaround is to use the brew
package and write your YAML front matter as a brew
template.
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
date: <%= format(Sys.time(), "%d %B, %Y") %>
author: baptiste
---
You can now use a brew_n_render
function that would preprocess the doc using brew
and then run in through rmarkdown
.
brew_n_render <- function(input, ...){
output_file <- gsub("\\.[R|r]md$", ".html", input)
brew::brew(input, 'temp.Rmd'); on.exit(unlink('temp.Rmd'))
rmarkdown::render('temp.Rmd', output_file = output_file)
}
To make this work with the KnitHTML
button in RStudio, you can write a custom output format that will automatically use brew
as the preprocessor. Using brew
to preprocess ensures that the knitr
code chunks in your document are untouched during the preprocessing stage. Ideally, the rmarkdown
package should expose the metadata in its API and allow users to run it through a custom function.
or, perhaps something like the following, see R Markdown Parameterized Reports
params:
reportDate:
input: date
label: 'Report Date:'
value: as.POSIXct(Sys.Date())