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.
codeoption can take a character vector of source code. For example:
You can also read an external file:
You can read as many scripts as you want:
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:
Read a C++ file:
code option, you can develop complicated code in your favorite editor, and read it into a code chunk of an R Markdown document.