16.2 Read external scripts into a chunk

There is a disadvantage of the source() method in Section 16.1. That is, you will not be able to see the source code by default. You can use source(..., echo = TRUE), but the source code will not be properly syntax highlighted. Besides, you need to be careful about the local argument of source(), as mentioned in Section 16.1. In this section, we introduce an alternative method that does not have these problems.

Basically, when you have one or more external scripts, you may read them via the file option of a chunk. The file option can take a character vector of file paths. Below we show a few examples.

  • You can read one external file:

    ```{r, file='your-script.R'}
    ```
  • You can read as many scripts as you want:

    ```{r, file=c('one.R', 'two.R')}
    ```

You can read scripts of other languages, too. See Chapter 15 for how to use other languages in R Markdown. Here are a few more examples on non-R code.

  • Read a Python script:

    ```{python, file='script.py'}
    ```
  • Read a C++ file:

    ```{Rcpp, file='source.cpp'}
    ```

With the file option, you can develop complicated code in your favorite editor, and read it into a code chunk of an R Markdown document.