knitr在HTML风格的评论中执行R代码块

时间:2017-06-08 13:49:44

标签: r rstudio knitr r-markdown

使用 Rstudio 编辑 Rmarkdown 文件,我使用HTML注释标记出我不想处理或输出的大块。这在Rstudio中工作得很好,它忽略了注释中的所有内容。但是,当我要求Rstudio编织文档时, knitr 正在评论中执行 R 代码块。

这是一个MWE .Rmd文件:

# Important stuff I want to see
This is what I want to see:
```{r}
pi # I like pi
```
<!---
**This section commented out, as not ready to be knit yet**
This is what I do not want to see:
```{r}
cake # I also like cake, but it's undefined
```
-->

这导致knitr失败并显示Error in eval(expr, envir, enclos) : object 'cake' not found ... Execution halted

是否有一种简单的方法可以注释掉整个Rmarkdown文件,以防止knitr在评论中执行R代码块?

我查看了global comment option for R markdown in knitrComments in Markdown以及https://yihui.name/knitr/,但没有找到解决方案。

3 个答案:

答案 0 :(得分:1)

考虑到jburkhardt使用eval=F的想法,这可以作为一种方法来执行块注释,其中knitr不执行R代码块:

Stuff I want to see...
```{r}
pi
```

<!--
This is added at the beginning of the comment:
```{r, include=FALSE}
knitr::opts_chunk$set(eval= FALSE)
```

Stuff I have commented out:

```{r}
cake
```

This is added to the end of the comment:
```{r, include=FALSE, eval=TRUE}
knitr::opts_chunk$set(eval= TRUE)
```
-->

More stuff I want to see:
```{r}
2*pi
```

它有点笨重,而且肯定不是防弹的(例如,knitr仍会运行它使用显式eval=true找到的任何代码块),但它适用于我的情况。

答案 1 :(得分:0)

选择{r}代码块之前和之后的行,并使用Control / Shift-C(pc)注释掉。你会得到这种语法;它不会编织,也不会出错。

<!-- **This section commented out, as not ready to be knit yet** -->
<!-- This is what I do not want to see: -->
<!-- ```{r} -->
<!-- cake # I also like cake, but it's undefined -->
<!-- ``` -->

答案 2 :(得分:0)

在第二段代码垃圾中,您可以设置eval=F,直到完成此部分代码。

<!--
**This section commented out, as not ready to be knit yet**
This is what I do not want to see:
```{r eval=F}
cake # I also like cake, but it's undefined
```
-->