YAML: How to use the current date in the Rmarkdown compilation?

Asked

Viewed 72 times

3

How to automatically include the current system date in the title of the document to be compiled by R-markdown?

When I try to include the system date in the field date through the YAML code: r format(Sys.time(), "%d de %B de %Y"), I get an error message:

---
title: "Exemplo"
author: "Socrates"
date: `r format(Sys.Date(), "%d de %B de %Y")`
output: html_document
---

Error in yaml::yaml.load(..., eval.expr = TRUE) : 
  Scanner error: while scanning for the next token at line 3, column 7 found character that cannot start any token at line 3, column 7
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
Execução interrompida

Note: Question and answer adapted from the Soen, for systems with language settings in Portuguese.

1 answer

4

For the date to be a valid field in YALM, it needs to be a string. For this reason, it is necessary to enclose the R code in quotation marks. Single quotes work better than double quotes in this case (the latter may cause errors when compiling to .docx or .pdf):

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

The YAML with the above code will produce in the header of your document a date text with the format: "November 12, 2020".

Note also that it is possible to edit the order and type of the desired date components, as well as the text that accompanies the date. For example, it is possible to include the day of the week with the element %A, producing the text: "Thursday, November 12, 2020".

---
title: "Exemplo"
author: "Socrates"
date: '`r format(Sys.Date(), "%A, %d de %B de %Y")`'
output: html_document
---

One possibility, if your system is configured in English and you are going to publish the content in Portuguese, is to use only the month in the numeric format, with the element %m. The code

'`r format(Sys.Date(), "%d/%m/%Y")`' 

will produce (today, the day I write) the text: "12/11/2020".

Note: adapted response from Soen to the Brazilian reality, according to the guidelines suggested by this Sopt Meta debate

Browser other questions tagged

You are not signed in. Login or sign up in order to post.