About debug messages in knitr

󰃭 2024-04-09

When writing markdown documents for processing with knitr, warnings and messages are usually shown in the output document.

Often, I also want to print debug messages to the console, e.g. for indicating progress etc.

For this purpose, I was using the code chunk option message=FALSE, which made the output of message() show up in the console rather than in the output document:

---
title: "Example document"
output:
  html_document

---

My doc does things.

```{r chunk1, echo=FALSE, message=FALSE}
message("DOING THINGS")
```

```{r chunk2, echo=FALSE, message=FALSE}
message("DOING OTHER THINGS")
```

Console output when knitting:

processing file: example.Rmd
  |..............                                                        |  20%
  ordinary text without R code

  |............................                                          |  40%
label: chunk1 (with options)
List of 2
 $ echo   : logi FALSE
 $ message: logi FALSE

DOING THINGS
  |..........................................                            |  60%
  ordinary text without R code

  |........................................................              |  80%
label: chunk2 (with options)
List of 2
 $ echo   : logi FALSE
 $ message: logi FALSE

DOING OTHER THINGS
  |......................................................................| 100%
  ordinary text without R code

At some point recently, I noticed that these messages no longer showed up in the console output, but were also not visible in the output documents and I was questioning myself if it actually ever worked.

After some googling, I found this post by yihui, the author of the knitr package. It turns out that in versions from 0.19 of the evaluate package used by knitr, the meaning of the chunk options warning and message changed, so that FALSE really means no output at all.

Instead, one needs to set the option to NA for getting the console output again, i.e.:

```{r chunk1, echo=FALSE, message=NA}
message("DOING THINGS")
```

Of course, these options can also be set globally for all code chunks, using:

knitr::opts_chunk$set(echo = FALSE, message = NA)

at the beginning of the document.

All chunk options and package options for knitr are shown here at knitr’s website and there are also ways for reusing options.