14.6 Save a group of chunk options and reuse them (*)

If you frequently use some chunk options, you may save them as a group and reuse them later only using the group name. This can be done with knitr::opts_template$set(name = list(options)). Then you can use the chunk option opts.label to refer to the group name. For example:

  1. ```{r, setup, include=FALSE}
  2. knitr::opts_template$set(fullwidth = list(
  3. fig.width = 10, fig.height = 6,
  4. fig.retina = 2, out.width = '100%'
  5. ))
  6. ```
  7. ```{r, opts.label='fullwidth'}
  8. plot(cars)
  9. ```

With opts.label = 'fullwidth', knitr will read chunk options from knitr::opts_template, and apply them to the current chunk. This can save you some typing effort. If a chunk option is to be used globally in a document, you should consider setting it globally (see Chapter 11).

You can override options read from opts.label, e.g., if you set fig.height = 7 in the chunk below, the actual fig.height will be 7 instead of 6.

  1. ```{r, opts.label='fullwidth', fig.height=7}
  2. plot(cars)
  3. ```

You can save an arbitrary number of grouped options, e.g., knitr::opts_template$set(group1 = list(...), group2 = list(...)).