KnitR/External Code Chunk

Introduction
If you have a large project in KnitR you devide to complete calculation task into subtasks that are implemented with a set of code chunks and functions in R. Especially when you R-Markdown file for KnitR get very large then it makes sense to place some subtasks in different external files wit R code. The external R files with code can be utilized later on in other projects and main R Markdown file import/loads these external files. This part of the learning resource is about using and storing external code.

Maintenance of External Code Chunks
External code chunk in R evolve during a projects and if they are improved, they improved in the external file. The benefit of that external code chunk file management is, that you easily update the improved file in other projects that used the same code chunk for further use. Especially debugging becomes much easier if you use the same filename for the specific code chunk e.g. moving_average.R for a specific implementation of the Moving Average in R for your project. If you perform a bugfix in the code of moving_average.R then you search for that file in your filesystem and replace the old version by the new version with the bugfix.

Handling external Code Chunks
There is different ways of handling external code. We start with a source file that has just code chunks in the main file. We extract the second code chunk of the source file and store the code in an external file externalcode.R

Source Main File
The source file in R Markdown format has the filename main.Rmd and looks like this:

--- title: "Code Chunk Example" output: html_document --- Set the variable x ```{r echo=FALSE} x <- 2 ``` Perform the variable y and perform a calculation ```{r echo=FALSE} y <- 5 res <- x * y ``` print the result in variable "res" ```{r echo=TRUE} res ```

Create the external Code Chunk
Now we copy the second code chunk into an external file externalcode.R and add the following first line: This line tells KnitR to store the R code chunk in the KnitR variable mycode that will contain the code chunk. For a standard execution of the external code in R this line does not matter, because it is regarded as a comment in R. So this external code can be used in R as well.
 * 1) @knitr mycode

The external code chunk externalcode.R calculates the product of two numbers $$a$$ and $$b$$ and stores the result in the variable res. The variable $$b$$ is defined in the code chunk and the variable $$a$$ was defined in the first code chunk:

b <- 5 res <- a * b
 * 1) @knitr mycode

Source Main File with external Code Chunk
Your modified R-Markdown that used the external code chunk will look like this:

--- title: "Code Chunk Example" output: html_document --- Set the variable x ```{r echo=FALSE} x <- 2 ``` ```{r echo=FALSE} knitr::read_chunk('externalcode.R') ``` Perform the variable y and perform a calculation ```{r echo=FALSE} < > ``` print the result in variable res ```{r echo=TRUE} res ```