baptiste
baptiste

Reputation: 77096

Evaluating R code in YAML header

Consider the following Rmd file,

---
title: "Untitled"
author: "baptiste"
date: "`r Sys.Date()`"
output: html_document
test: "`r paste('_metadata.yaml')`"
---

```{r}
cat(rmarkdown::metadata$test)
```

enter image description here

The date is processed (knitted) by R before being passed to pandoc for conversion to md and html. The custom field test, however, is unevaluated.

What's the difference? Can one force knitr/rmarkdown to evaluate an arbitrary field in the yaml header?

Note: the actual purpose is not to just print() a filename as in this dummy example, but to load an external yaml file containing metadata (author information), process it with R, and output a string that will be injected in the document.

Upvotes: 11

Views: 4273

Answers (2)

Stibu
Stibu

Reputation: 15897

The standard metadata field data and your custom field test are not actually treated any differently. This code:

---
title: "Untitled"
author: "baptiste"
date: "`r Sys.Date()`"
output: 
  html_document: 
    keep_md: yes
test: "`r paste('_metadata.yaml')`"
---

```{r}
cat(rmarkdown::metadata$date)
cat(rmarkdown::metadata$test)
```

leads to the following output:

enter image description here

As you can see, also date was not evaluated. I have not found any functionality in the rmarkdown or knitr packages. But the following simple function does the trick at least for your simple example:

---
title: "Untitled"
author: "baptiste"
date: "`r Sys.Date()`"
output: 
  html_document: 
    keep_md: yes
test: "`r paste('_metadata.yaml')`"
---

```{r}
eval_meta <- function(x) eval(parse(text = gsub("`|r", "", x)))
eval_meta(rmarkdown::metadata$date)
eval_meta(rmarkdown::metadata$test)
```

enter image description here

Whether that works in your more complex situation is another question, however.

Upvotes: 4

user2554330
user2554330

Reputation: 44788

It does evaluate the code. If you run foo.Rmd with

rmarkdown::render("foo.Rmd", clean = FALSE)

you'll see an intermediate file (the pandoc input) called foo.knit.md left behind. It will look like this:

---
title: "Untitled"
author: "baptiste"
date: "2017-08-12"
output: html_document
test: "_metadata.yaml"
---


```r
cat(rmarkdown::metadata$test)
```

```
## `r paste('_metadata.yaml')`
```

I don't know how to see that from within the document (your example shows that metadata$test doesn't work), but there's probably some trick or other to get at it.

Upvotes: 4

Related Questions