11.1 Use variables in chunk options
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:
```{r}
my_width <- 7
plot(cars)
Below is an example of using an `if-else` statement in a chunk option:
fig_small <- FALSE # change to TRUE for larger figures
width_small <- 4
width_large <- 8
plot(cars)
And we have one more example below in which we evaluate (i.e., execute) a code chunk only if a required package is available:
library(leaflet)
leaflet() %>% addTiles()
```
In case you do not know it, require('package') returns TRUE if the package is available (and FALSE if not).
