C. Murtaugh
C. Murtaugh

Reputation: 571

RStudio - changing default code chunk

In RStudio, when I insert a new code chunk in my .Rmd file (Code>Insert chunk, or Ctrl-Alt-I), by default it has the header {r}. I'd like to have it instead default to the knitr option {r, message=F}, which I find makes for nicer final report outputs. Is there a way to change the default code header in RStudio? Thanks!

Upvotes: 3

Views: 2270

Answers (2)

Dylan_Gomes
Dylan_Gomes

Reputation: 2232

I know that this is an old question, but I have come across this issue a few times, and would like to expand on @Keith Hughitt's great answer,

If you include Keith's code

```{r setup}
knitr::opts_chunk$set(message=FALSE)
```

Within the first code chunk, then these will be the global options for all the following code chunks.

https://rmarkdown.rstudio.com/lesson-3.html says this another way: "Knitr will treat each option that you pass to knitr::opts_chunk$set as a global default that can be overwritten in individual chunk headers."

That is, it is more efficient to set the global options once, and then overwrite it in future chunks if need be.

For example,

```{r setup}
knitr::opts_chunk$set(message=F, echo=F) # set multiple global options here
```

```{r block1, echo=T} # override some global options
# code
```

```{r block2, message=T} # override different global options
# code
```

```{r block3} # we don't override anything so the global options set above are used
# code
```

block1 will echo the code, but show no messages. block2 will not echo the code, but will show messages. block3 will not echo the code or show messages because we set the global options in the setup block.

Upvotes: 2

Keith Hughitt
Keith Hughitt

Reputation: 4960

I'm not sure about changing the default chunk text, but to achieve the same effect, you could also modify the default chunk options using opts_chunk$set():

opts_chunk$set(message=FALSE)

More info: http://yihui.name/knitr/options/

Upvotes: 7

Related Questions