Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing external source in knitr and printing the external code chunk

Tags:

r

knitr

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?

like image 663
Chris Shaw Avatar asked Feb 06 '26 21:02

Chris Shaw


1 Answers

You may try this:

In the main body:

```{r runanalysis, code=readLines('../src/rf-model-caret.R'), echo=FALSE, eval=TRUE}
```

In the appendix:

```{r runanalysis, code=readLines('../src/rf-model-caret.R'), echo=TRUE, eval=FALSE}
```
like image 200
Yihui Xie Avatar answered Feb 08 '26 10:02

Yihui Xie