'Rendering quietly not working if the chunk has message = FALSE

I want to render an R Markdown file quietly, i.e nothing should be displayed in the console. Let foo.Rmd be the following file:

---
title: "Foo"
output: 
    html_vignette

vignette: >
  %\VignetteIndexEntry{Foo}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}

---

```{r}
library(survey)
```

Using rmarkdown::render("foo.Rmd", quiet = TRUE) works correctly. However, if I add message=FALSE to the chunk, then some messages generated by the loading of the package appear:

---
title: "Foo"
output: 
    html_vignette

vignette: >
  %\VignetteIndexEntry{Foo}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}

---

```{r, message=FALSE}
library(survey)
```
> rmarkdown::render("foo.Rmd", quiet = TRUE)
Loading required package: grid
Loading required package: Matrix
Loading required package: survival

Attaching package: 'survey'

The following object is masked from 'package:graphics':

    dotchart

(Note that you have to restart the session each time you add or remove message=FALSE, as the messages are displayed only once per session.)

Is this a bug? Or am I missing something?



Solution 1:[1]

This was solved on this Github issue. In summary, there are two ways to fix this:

  • suppressMessages(rmarkdown::render("foo.Rmd", quiet = TRUE))
  • callr::r(function() rmarkdown::render("test.Rmd"))

Solution 2:[2]

I think, it is not necessarily a "bug". R considers that messages should be displayed anyway. I think quiet argument in render function is working fine to suppress anything while it is sure that messages are displayed somewhere(here in Rmarkdown output).
But when you suppress messages in Rmarkdown output, printing messages in console supersedes quiet function, Because R wants to display messages in a place(could be in "output" or in "console").
A same issue about bash chunk had been rised in github, and I think that is somehow similar to your issue.
Your issue also could be rised in knitr github, so R developers would consider changing this option.

Of course you know, One way to get rid of messages completely is using sink function to divert all messages to a file.

Then you can suppress messages in "output" by message = F as you did, and also suppress messages in console.

Restarting R session...

> divert_file <- file("divert_file.txt",open ="wt")
> sink(divert_file, type = "message")
> rmarkdown::render("foo.Rmd", quiet = T)
>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bretauv
Solution 2