When to use YAML vs when to use setup code chunk

I asked on Twitter recently about when it made sense to set things like default figure width and height in the YAML of an RMarkdown document versus in the setup code chunk. @yihui helpfully responded with the following:

The YAML approach allows you to set options globally for a specific output format (e.g. html_document). The setup chunk approach sets chunk options globally for the document regardless of the output format (unless you set them conditionally, e.g. if (knitr::is_html_output()) set)

He asked me to post this here so others can find it, which I'm doing now. Hope it's helpful for others!

4 Likes

Thank you! Since we don't have the limit on the number of characters here, I can type out the characters that I wasn't able to finish on Twitter (which is why I strongly recommend asking questions on forums before trying Twitter):

The YAML approach allows you to set options globally for a specific output format, e.g.

html_document:
  fig_width: 10
pdf_document:
  fig_width: 5

The setup chunk approach sets chunk options globally for the document regardless of the output format, e.g.

```{r, setup}
knitr::opts_chunk$set(fig.width = 10)
```

unless you set the options conditionally, e.g. only for HTML output:

if (knitr::is_html_output()) knitr::opts_chunk$set(fig.width = 10)
3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.