Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

r - Executing external source in knitr and printing the external code chunk

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}
```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...