16.1 Source external R scripts

If your R Markdown document has a large amount of code, you may consider putting some code in external R scripts, and run these scripts via source() or sys.source(), e.g.,

```{r, include=FALSE}
source("your-script.R", local = knitr::knit_global())
# or sys.source("your-script.R", envir = knitr::knit_global())
```

We recommend that you use the argument local in source() or envir in sys.source() explicitly to make sure the code is evaluated in the correct environment, i.e., knitr::knit_global(). The default values for them may not be the appropriate environment: you may end up creating variables in the wrong environment, and being surprised that why certain objects are not found in later code chunks.

Next in the R Markdown document, you can use objects created in these scripts (e.g., data objects or functions). This way will not only make your R Markdown document cleaner, but also make it more convenient for you to develop R code (e.g., debugging R code is often easier with pure R scripts than R Markdown).

Note that we used include = FALSE in the above example because we only want to execute the script without showing any output. If you do want output, you may remove this chunk option, or use the options in Section 11.7 to selectively hide or show different types of output.