1
votes

Using Rstudio to edit an Rmarkdown file, I use HTML comments mark out large blocks that I don't want to have processed or in the output. This works just fine in Rstudio, which ignores everything in the comments. However, when I ask Rstudio to knit the document, knitr is executing the R code blocks in the comments.

Here's an MWE .Rmd file:

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

This causes knitr to fail with Error in eval(expr, envir, enclos) : object 'cake' not found ... Execution halted

Is there an easy way to comment out whole swathes of an Rmarkdown file which prevents knitr from executing the R code chunks in the comments?

I have looked at global comment option for R markdown in knitr and Comments in Markdown, as well as https://yihui.name/knitr/, but didn't find a solution.

3
Just selecting the whole part and do Ctrl + Shift + C ?Martin Schmelzer
Thanks Yihui -- I will remember to look there next time I have an issue. Thanks also for a fantastic tool!chriss

3 Answers

1
votes

Taking jburkhardt's idea of using eval=F, this works as a way of doing block comments where knitr does not execute the R code blocks:

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

It's a bit clunky, and it's certainly not bulletproof (for example, knitr will still run any code blocks it finds with explicit eval=true), but it works in my case.

0
votes

Select lines before and after the {r} code chunk and use Control/Shift-C (pc) to comment out. You will get this kind of syntax; it won't knit, and won't give an error.

<!-- **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 -->
<!-- ``` -->
0
votes

In the second code junk you could set eval=F until you have finished this part of your code.

<!--
**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
```
-->