Knit:不要取一大块金银丝

ant*_*nio 5 r knitr r-markdown

考虑以下test.Rmd

```{r setup, purl=FALSE}
opts_chunk$set(purl=FALSE)
opts_template$set(nopurl = list(purl=FALSE))
```     

```{r test1}
print(1)
```

```{r test2, opts.label='nopurl'}
print(2)
```

```{r test3, purl=FALSE}
print(3)
```
Run Code Online (Sandbox Code Playgroud)

purl('test.Rmd')给出test.R,其中没有一个 test* 块应该被 purled,但是:

## ----test1---------------------------------------------------------------
print(1)


## ----test2, opts.label='nopurl'------------------------------------------
print(2)
Run Code Online (Sandbox Code Playgroud)

test3尽管有全局选项 opts_chunk$set(purl=FALSE)和标签,只有没有被purled,其余的都是purled nopurl
为什么?

ant*_*nio 2

根据亿辉的反馈,走的路是这样的:

```{r setup, purl=FALSE}
knit_hooks$set(purl = hook_purl)
opts_template$set(nopurl = list(purl=FALSE))
opts_template$set(dopurl = list(purl=TRUE))
```

```{r test}
print(1)
```

```{r test2, opts.label='nopurl'}
print(2)
```

```{r test3, opts.label='dopurl'}
print(3)
```
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您不需要:

purl('test.Rmd') 
Run Code Online (Sandbox Code Playgroud)

您只需:

knit('test.Rmd') 
Run Code Online (Sandbox Code Playgroud)

并获取常规文件test.mdtest.R文件。后者如下:

## ----test----------------------------------------------------------------
print(1)

## ----test3, opts.label='dopurl'------------------------------------------
print(3)
Run Code Online (Sandbox Code Playgroud)

如您所见,给定knit_hooks$set(purl = hook_purl),块的默认行为是 Purling。

在实际使用中nopurldopurl会收集更多选项与(无)purling 一起设置。
无论如何,在考虑以下注意事项时:

注意:不能保证“purl()”生成的 R 脚本可以重现“knit()”中完成的计算。“knit()”过程可能相当复杂(块选项的特殊值、自定义块挂钩、R 之外的计算引擎以及“envir”参数等)。如果您想在“knit()”生成的报告中重现计算,请务必使用“knit()”,而不是仅仅执行“purl()”生成的 R 脚本。这似乎是显而易见的事情,但有些人就是不明白。

当不需要 purl 时,总是使用 knit_hooks$set(purl = hook_purl)和设置似乎是明智的。purl=FALSE