15.2 Read external scripts into a chunk

There is a disadvantage of the source() method in Section 15.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. In this section, we introduce an alternative method that does not have this drawback.

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=readLines('your-script.R')}
```

You can read as many scripts as you want:

```{r, include=FALSE}
read_files <- function(files) {
  unlist(lapply(files, readLines))
}
```

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

You can read scripts of other languages, too. See Chapter 14 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=readLines('script.py')}
```

Read a C++ file:

```{Rcpp, code=readLines('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.