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:

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

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

    1. ```{r, include=FALSE}
    2. read_files <- function(files) {
    3. unlist(lapply(files, xfun::read_utf8))
    4. }
    5. ```
    6. ```{r, code=read_files(c('one.R', 'two.R'))}
    7. ```

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:

    1. ```{python, code=xfun::read_utf8('script.py')}
    2. ```
  • Read a C++ file:

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

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.