knitr - 从'purl(...)`中排除块?

mat*_*fee 19 r knitr

当我对文档进行purl/tangle以将R块提取到脚本中时,有什么方法可以:

  • 排除一个任意的块(按名称说)?
  • 如果没有,排除一个块if eval=F(或者我可以定义一个chunk hook/option include=F)?

例如,假设我有以下Rmd:

```{r setup, echo=F}
library(MASS)
```
First, we perform the setup (assume for some reason I need to evaluate `setup`
silently before I wish to display the chunk to the user, hence the repetition)
```{r setup, eval=F}
```

Here's the function I've been explaining:
```{r function}
plus <- function (a, b) a + b
```

And here's an example of its use:
```{r example}
plus(1, 2)
```
Run Code Online (Sandbox Code Playgroud)

纠结的脚本看起来像这样:

## @knitr setup, echo=F
library(MASS)   

## @knitr setup, eval=F
library(MASS)

## @knitr function
plus <- function (a, b) a + b

## @knitr example
plus(1, 2)
Run Code Online (Sandbox Code Playgroud)

我有这样的想法,因为我想要评估特定的块,它们至少不应该出现在输出中(在上面的例子中,第二个setup块).

另外,对于纠结的输出,将一些块标记为"不可见"对我来说会很好.我不希望example我的输出脚本中的块(为了文档的目的,它在Rmd中很好,但我希望能够纠结Rmd然后只是source('myfile.r')如果我想使用该plus函数,而不必担心这些额外的例子正在执行.目前我纠结了Rmd,然后手动编辑出我不想从剧本中取出的块,这似乎违背了只编写一个Rmd的原则,它将提供文档和脚本而无需额外的努力.)

Yih*_*Xie 22

knitr1.3开始,有一个新的块选项purl = TRUE/FALSE允许一个包含/排除某些代码块purl().

```{r test, purl=FALSE}
library(MASS)
```
Run Code Online (Sandbox Code Playgroud)


The*_*ell 7

纠结处理块目前没有扩展params,但我们可以这样做......

# See `?trace` documentation for details.
bdy <- as.list( body( knitr:::process_tangle.block ) )
trace.at <- which( grepl(".*opts_chunk\\$merge.*",
                         as.list( body( knitr:::process_tangle.block ) ) ) )
tracer <- quote({
  # Code borrowed from normal chunk procesing.
  af = opts_knit$get('eval.after'); al = opts_knit$get('aliases')
  if (!is.null(al) && !is.null(af)) af = c(af, names(al[af %in% al]))
  for (o in setdiff(names(params), af)) params[o] = list(eval_lang(params[[o]]))
  # Omit this if using lastest knitr source from github.
  if( isFALSE( params$include ) ) {
    tmp <- knit_code$get();
    tmp[[params$label]] <- "";
    knit_code$restore(tmp)
  }
})

trace( knitr:::process_tangle.block, tracer=tracer, at=trace.at, print=FALSE )
Run Code Online (Sandbox Code Playgroud)

然后可以使用选项参数控制purl()排除...

```{r setup, echo=TRUE, results='hide'}
library(MASS)
````

First, we perform the setup (assume for some reason I need to evaluate `setup`
silently before I wish to display the chunk to the user, hence the repetition)
```{r setup2, ref.label="setup", echo=FALSE, results='markup'}
```

Here's the function I've been explaining:
```{r function}
plus <- function (a, b) a + b
```

And here's an example of its use:
```{r example, eval=!opts_knit$get("tangle") }
plus(1, 2)
```

And here's another example of its use:
```{r example2, include=!opts_knit$get("tangle") }
plus(3, 3)
```
Run Code Online (Sandbox Code Playgroud)