16.3 Read multiple code chunks from an external script (*)

In Section 16.2, we introduced a way to read code into a single code chunk. In this section, we introduce one method to read multiple code chunks from an external script. The key is that you need to label the code in the script, and you can use the same labels in the code chunks in your R Markdown document, so the code in the external script can be mapped to the code chunks via the function knitr::read_chunk(). To label a block of code in a script, you write the label after ## ---- (optionally, you can add a series of dashes to the end of this line). One script can contain multiple labeled code blocks, e.g.,

## ---- test-a --------
1 + 1

## ---- test-b --------
if (TRUE) {

We assume that the filename of the above script is test.R. In the R Markdown document, we can read it via knitr::read_chunk(), and use the code in code chunks with the labels, e.g.,

Read an external script:

```{r, include=FALSE, cache=FALSE}

Now we can use the code, e.g.,

```{r, test-a, echo=FALSE}

```{r, test-b, fig.height=4}

Note that we use knitr::read_chunk() mainly for its side effect, so please make sure the code chunk in which you call this function is not cached (see Section 11.4 for the explanation).

Like methods introduced in Section 16.1 and Section 16.2, this method also gives you the flexibility of developing code in a separate environment.