11.1 Use variables in chunk options

Usually chunk options take constant values (e.g., fig.width = 6), but they can actually take values from arbitrary R expressions, no matter how simple or complicated the expressions are. A special case is a variable passed to a chunk option (note that a variable is also an R expression). For example, you can define a figure width in a variable in the beginning of a document, and use it later in other code chunks, so you will be able to easily change the width in the future:

  1. ```{r}
  2. my_width <- 7
  3. ```
  4. ```{r, fig.width=my_width}
  5. plot(cars)
  6. ```

Below is an example of using an if-else statement in a chunk option:

  1. ```{r}
  2. fig_small <- FALSE # change to TRUE for larger figures
  3. width_small <- 4
  4. width_large <- 8
  5. ```
  6. ```{r, fig.width=if (fig_small) width_small else width_large}
  7. plot(cars)
  8. ```

And we have one more example below in which we evaluate (i.e., execute) a code chunk only if a required package is available:

  1. ```{r, eval=require('leaflet')}
  2. library(leaflet)
  3. leaflet() %>% addTiles()
  4. ```

In case you do not know it, require('package') returns TRUE if the package is available (and FALSE if not).