15.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", envir = knitr::knit_global())
# or sys.source("your-script.R", envir = knitr::knit_global())

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 9.5 to selectively hide or show different types of output.