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 and pass the content to the code option of a chunk. The code option can take a character vector and treat it as the content of the code chunk. Below we show a few examples.

  • The code option can take a character vector of source code. For example:

    ```{r, code=c('1 + 1', 'if (TRUE) plot(cars)')}
  • You can also read an external file:

    ```{r, code=xfun::read_utf8('your-script.R')}
  • You can read as many scripts as you want:

    ```{r, include=FALSE}
    read_files <- function(files) {
      unlist(lapply(files, xfun::read_utf8))
    ```{r, code=read_files(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, code=xfun::read_utf8('script.py')}
  • Read a C++ file:

    ```{Rcpp, code=xfun::read_utf8('file.cpp')}

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