Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional evaluation of knitr chunks with Rstudio "Run" button

I am using conditional evaluation using the eval option in the chunk header. If I write eval=FALSE in the header, the chunk is not evaluated when I knit the document, and also not when I use the Run All (Ctrl+Alt+R) from the Rstudio menu.

The problem arises when I try to provide eval with a variable, e.g. the example below:

```{r setup}
ev_cars = TRUE
ev_pressure = FALSE
```

## First chunk

```{r cars, eval=ev_cars}
summary(cars)
```

## Second chunk

```{r pressure, echo=FALSE, eval = ev_pressure}
plot(pressure)
```

In this example, when I run knitr, then the first chunk is evaluated and the second chunk is not (because ev_pressure=FALSE). However, when I try to run using he Run All (Ctrl+Alt+R) from the Rstudio menu, both chunks are evaluated.

Is there a way to overcome this issue?

I am using Rstudio v 1.1

All the best,

Gil

like image 518
Gil Hornung Avatar asked Oct 29 '22 22:10

Gil Hornung


1 Answers

EDIT: {The chunk options are only used when you knit. The Run All command does not knit the document but execute what is inside chunks, without reading chunks arguments.} This is not totally true, indeed, if eval is set to FALSE or TRUE, it is taken into account.
{Thus, a} way to add options like not executing code inside chunks when running Run All would be to do it in the old way with an if inside the chunk.

```{r setup}
ev_cars = TRUE
ev_pressure = FALSE
```

## First chunk

```{r cars}
if (ev_cars) {
  summary(cars)
}
```

## Second chunk

```{r pressure, echo=FALSE}
if (ev_pressure) {
  plot(pressure)
}
```

The code is then heavier in this way. But if you use Run All, why not directly knit it ?

like image 149
Sébastien Rochette Avatar answered Nov 08 '22 13:11

Sébastien Rochette