maxpe
maxpe

Reputation: 316

Knit child documents in standalone mode

According to https://yihui.org/knitr/demo/child/ it is possible to knit child documents on their own by using set_parent() in a chunk.

I tried that:

knitr::set_parent("<PATH TO MAIN FILE>")

But that does not seem to work. Knitting the child does not take information in the YAML section of the parent into account. What am I doing wrong here?

Upvotes: 1

Views: 376

Answers (1)

Yihui Xie
Yihui Xie

Reputation: 30124

Here is a function that you can use to input the YAML frontmatter of an arbitrary Rmd file into another Rmd file:

input_yaml = function(file) {
  lines = xfun::read_utf8(file)
  meta = rmarkdown:::partition_yaml_front_matter(lines)$front_matter
  knitr::asis_output(paste(meta, collapse = '\n'))
}

If you don't prefer :::, you could also use:

input_yaml = function(file) {
  meta = rmarkdown::yaml_front_matter(file)
  meta = c('---', yaml::as.yaml(meta), '---')
  knitr::asis_output(paste(meta, collapse = '\n'))
}

Then in the child document, you may do this:

```{r, echo=FALSE}
input_yaml('parent.Rmd')
```

This is a child document without YAML.

Upvotes: 3

Related Questions