Mutator
Mutator

Reputation: 15

Is there a way to extract the date information from the YAML header in Rmarkdown for use in an R chunk?

I am using Rmarkdown to make an electronic lab notebook template. I am using the date entry as my experiment date and I would like to use that same date information for generating file names in the R chunks without having to continually retype the date. Is there a command that can extract this information from the YAML header?

Upvotes: 1

Views: 468

Answers (1)

r2evans
r2evans

Reputation: 160742

From outside the rmarkdown document, rmarkdown::yaml_front_matter() should work well for you.

However, if you're talking about inside (within a chunk itself), then I think you should look into Parameterized RMarkdown documents; specifically, include a params:\n date: !r Sys.date(), and elsewhere in your document use params$date in R.

For example:

---
title: My Document
output: html_document
params:
  date: !r Sys.Date()
---

## Header

Inline, today's date is `r params$date`.

```{r}
cat("In a code chunk, today's date is ", format(params$date, format = "%b %d, %Y"), "\n")
```

rendered rmarkdown document

If you need to specific a specific date other than "today", you can change the value when you render it,

rmarkdown::render('foo.Rmd', params=list(date="2020-01-01"))

(Though in this example, "2020-01-01" will not be reformatted properly within my example, since format won't be getting an actual Date-class object. Topic for a different day :-)

Upvotes: 1

Related Questions