J_F
J_F

Reputation: 10352

How to set different global options in knitr RMD file

I want to exclude a lot of code chunks in my RMD file and had the idea to set the global options with eval = FALSE before and then eval = TRUE afterwards. But this is not working.

Here a toy example:

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, eval = FALSE)
```
## will not be executed because global option `eval = FALSE`
```{r}
x+y
```

```{r setup II, include=FALSE}
knitr::opts_chunk$set(eval = TRUE, echo = TRUE)
```
## Should give `2` in final document, because eval = TRUE
## NOT working as expected
```{r}
1+1
```

## This is working as expected
```{r, eval = TRUE}
1+1
```

Here the result:

enter image description here

Is this a bug or a feature? For my opinion this works counter-intuitive ...

Upvotes: 0

Views: 5218

Answers (1)

Yihui Xie
Yihui Xie

Reputation: 30124

It is not a bug or feature, but expected. You set eval = FALSE in the first code chunk, which means the second code chunk will not be evaluated, hence knitr::opts_chunk$set(eval = TRUE, echo = TRUE) was not executed at all. Then eval is still FALSE for the third code chunk.

You need to set eval = TRUE on the second code chunk:

```{r setup II, include=FALSE, eval=TRUE}
knitr::opts_chunk$set(eval = TRUE, echo = TRUE)
```

Upvotes: 8

Related Questions