Evaluation of the R code in the 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 passing pandoc to convert to md and html. However, a custom field is testnot evaluated.

Who cares? Is it possible to get knitr / rmarkdown to evaluate an arbitrary field in the yaml header?

Note. The actual goal is not just print()the file name, as in this example, but to load the external yaml file containing metadata (information about the author), process it with R and display the line that will be entered in the document.

+4
source share
2 answers

He evaluates the code. If you run foo.Rmd with

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

( pandoc) foo.knit.md . :

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


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

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

, ( , metadata$test ), , , - , .

+3

data test . :

---
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)
```

:

enter image description here

, date . rmarkdown knitr. :

---
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

, , .

+2

Source: https://habr.com/ru/post/1683560/


All Articles