在Knitr中执行外部源并打印外部代码块 [英] Executing external source in knitr and printing the external code chunk

查看:111
本文介绍了在Knitr中执行外部源并打印外部代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ProjectTemplate和Knitr生成报告.大部分分析结果存储在src目录中,而报告中包含演示文稿R markdown.

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:

  • 分析必须进行两次-首先在主文档的源代码中进行,然后在附录中再次进行代码生成.
  • 读取编织块,然后立即再次引用以显示代码

是否有更好的方法来实现在主文档中执行外部源并在附录中打印代码的目标?

Is there a better way to achieve the goal of executing external source in the main document and printing the code in the appendix?

推荐答案

您可以尝试以下方法:

在主体中:

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

在附录中:

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

这篇关于在Knitr中执行外部源并打印外部代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆