I am using SQL blocks in an RMarkdown document, and I want the echo option to default to FALSE for all of them – but only for sql blocks, not others.
I know I can set knitr::opts_chunk$set(echo = TRUE), but that would set it for all chunks.
I am using SQL blocks in an RMarkdown document, and I want the echo option to default to FALSE for all of them – but only for sql blocks, not others.
I know I can set knitr::opts_chunk$set(echo = TRUE), but that would set it for all chunks.
As Yihui suggested in a comment, the proper way to do this is to use an option hook. The following sets echo=FALSE for sql chunks and echo=TRUE otherwise:
knitr::opts_hooks$set(echo = function(options) {
options$echo <- options$engine != "sql"
return(options)
})
I'll leave my original answer below … for entertainment. It's a workaround, required in a hypothetical parallel universe without option hooks.
You can query the current engine via opts_current$get("engine"). Based on this, you can use the following function (and extend it however you like) to determine the desired value for echo:
conditionalDefaut_echo <- function() {
return(opts_current$get("engine") != "sql")
}
The challenge is to evaluate this function whenever parsing a new chunk. This can be achieved with quote:
opts_chunk$set(echo = quote(conditionalDefaut_echo()))
To be honest, I am not sure how reliable this is – this kind of metaprogramming depends on the internal workings of knitr and might break in the future. (Maybe Yihui wants to comment on this …)
A full example with engines r and asis, where echo is FALSE for asis chunks and TRUE otherwise:
```{r}
library(knitr)
conditionalDefaut_echo <- function() {
return(opts_current$get("engine") != "asis")
}
opts_chunk$set(echo = quote(conditionalDefaut_echo()))
```
```{asis}
I'm invisible.
```
```{r}
print(1) # code visible
```