4.19 Put together all code in the appendix (*)

Unless the target readers are highly interested in the computational details while they read a report, you may not want to show the source code blocks in the report. For this purpose, you can set the chunk option echo = FALSE to hide the source code instead, so readers will not be distracted by the program code for computing. However, the source code is still important for the sake of reproducible research. Sometimes readers may want to verify the computational correctness after they have finished reading the report. In this case, it can be a good idea to hold all code blocks in the body of the report, and display them at the end of a document (e.g., in an appendix).

There is a simple method of extracting all code chunks in a document and putting them together in a single code chunk using the chunk option ref.label and the function knitr::all_labels(), e.g.,

# Appendix: All code for this report

```{r ref.label=knitr::all_labels(), echo=TRUE, eval=FALSE}
```

Please read Section 14.1.3 if you are not familiar with the chunk option ref.label.

The function knitr::all_labels() returns a vector of all chunk labels in the document, so ref.label = knitr::all_labels() means retrieving all source code chunks to this code chunk. With the chunk options echo = TRUE (display the code) and eval = FALSE (do not evaluate this particular code chunk because all code has been executed before), you can show a copy of all your source code in one code chunk.

Since ref.label can be a character vector of arbitrary chunk labels, you can certainly filter the labels to decide a subset of code chunks to display in the code appendix. Below is an example (credits to Ariel Muldoon) of excluding the labels setup and get-labels:

```{r get-labels, echo = FALSE}
labs = knitr::all_labels()
labs = setdiff(labs, c("setup", "get-labels"))
```

```{r all-code, ref.label=labs, eval=FALSE}
```

You can also filter code chunks using the arguments of knitr::all_labels(). For example, you may use knitr::all_labels(engine == "Rcpp", echo == FALSE) to obtain all your code chunks that use the Rcpp engine (engine == "Rcpp") and are not displayed in the document (echo = FALSE). If you want precise control over which code chunks to display in the appendix, you may use a special chunk option appendix = TRUE on certain code chunks, and ref.label = knitr::all_labels(appendix == TRUE) to obtain the labels of these code chunks.