I use ProjectTemplate and Knitr to produce reports. Most of the analysis is stored in the src directory, whilst the report contains the presentation R markdown.
I would like the main text to include only the results of the analysis, and the document appendix to contain some code chunks from the analysis. The only way I have found to achieve this is as follows:
First, run the actual analysis in the main body of the document:
```{r runanalysis, warning=FALSE, message=FALSE}
# run the analysis code to generate the objects
source('../src/rf-model-caret.R')
```
Secondly, in the appendix, two knitr chunks are needed. The first reads in the actual code (and executes it). The second displays the code.
```{r analysis, eval=TRUE, echo=FALSE}
knitr::read_chunk('../src/rf-model-caret.R')
```
```{r analysis2, ref.label="analysis", eval=FALSE, echo=TRUE}
```
This works but seems very inefficient because:
- The analysis has to be run twice - firstly in the source in the main document, and again in the appendix just to produce the code.
- reading a knitr chunk and then referencing it again immediately to display the code
Is there a better way to achieve the goal of executing external source in the main document and printing the code in the appendix?