97

I have a .Rpres file in RStudio. I would like to include code, but not have it run (I am only showing the code to explain how it works). Is it possible to accomplish this (and ensure that it will not produce errors, because it is not running)?

3 Answers3

146

Have you tried eval=FALSE in the knitr code chunk options? For example:

```{r, eval=FALSE}
print("Don't run me")
```
alex
  • 345
  • 2
  • 10
hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
  • 4
    didn´t you miss a comma: {r , eval=FALSE} ? – LucasMation Jul 18 '16 at 20:40
  • 1
    `eval=FALSE` **does not** check whether code is valid. – Cryptor Mar 22 '17 at 17:09
  • OP can run it w/o that to test then turn on `eval=FALSE` for production. – hrbrmstr Mar 22 '17 at 17:11
  • 1
    @LucasMation, Rmarkdown syntax does not include a comma between the language specifier and the first knitr option, so hrbrmstr's answer is ok without the comma. For example see Yihui's examples on the [gitlab repo](https://github.com/yihui/knitr-examples/blob/master/007-text-output.Rmd) – ichbinallen Mar 27 '20 at 20:31
  • Is there a way to apply this to the whole document without typing it for each chunk? – bandcar Sep 27 '22 at 22:04
32

{r, eval=F, echo=T} will include the R source code in the output file while it is not evaluated

JdP
  • 714
  • 7
  • 14
  • How can I do this at once ie one global `eval=FALSE`. Of course one could use RegEx to replace all parts but how can I render but not run any code in the doc? – NelsonGon Mar 09 '20 at 09:14
  • Use the `knitr::opts_chunk$set` config to set `eval = FALSE` globally. ```{r setup, include=FALSE} knitr::opts_chunk$set(eval = FALSE) ``` – kategorically Jan 11 '21 at 16:49
9

Posting for anyone who may come across this like I have. I've found that for small examples (if you don't want to use chunks), you can also just use back ticks like you would with regular markdown inline, but just don't add the "r" at the beginning:

`plot(cars)`

Will print the code itself, but will not print the plot.

Meghan H.
  • 91
  • 1
  • 3