Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commenting in rmarkdown/knitr to prevent R evaluation

The recommendation for commenting in .Rmd documents to use HTML commenting <!-- comment here --> is insufficient. I'd like to comment out a section of my document that includes inline evaluations:

I haven't defined `x` yet.

<!-- So when I say that `x` is `r x` in the text, I'd like to comment it out -->

Knitting this fails:

#   |.................................................................| 100%
#    inline R code fragments
# 
# 
# 
# 
# processing file: test.Rmd
# Quitting from lines 2-3 (test.Rmd)
# Error in eval(expr, envir, enclos) : object 'x' not found
# Calls: <Anonymous> ... in_dir -> inline_exec -> withVisible -> eval -> eval
# Execution halted

One option is to comment each inline section:

I haven't defined `x` yet.

So when I say that `x` is `r #x` in the text, I'd like to comment it out

But this suffers if I'd like to comment out a whole paragraph with several such inline calculations, for example. Is there a more canonical way of doing this?

like image 306
MichaelChirico Avatar asked May 04 '17 13:05

MichaelChirico


1 Answers

As @NicE said, knitr goes first to evaluate your code, in particular because there may be inline R code evaluation or other R variable dependent text, which then need to be evaluated as markdown syntax. For instance, this included in rmarkdown:

Define if bold `r bold <- TRUE`  
This text is `r ifelse(bold, "**bold**", "_italic_")`.

Gives:

Define if bold
This text is bold.

Then, I think the only way to insert comments without evaluating them is to embed them in a chunk with eval=FALSE & echo=FALSE

```{r, eval=FALSE, echo=FALSE}
So when I say that `x` is `r x` in the text, I'd like to comment it out
```
like image 175
Sébastien Rochette Avatar answered Nov 01 '22 02:11

Sébastien Rochette