Pretty errors, warnings and messages in R Markdown

[This article was first published on R on Tea & Stats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

When knitting an R Markdown document to HTML output, R chunks can produce warnings, errors or messages.

Normally these messages look like any other console output:

R Markdown alert messages

Pretty ugly, and usually something I find myself trying to hide at the earliest opportunity.

But if you’re using R Markdown’s default template, which uses Twitter Bootstrap, you can promote warnings, errors and messages to first-class citizens.

What if you could have them looking like this?

Bootstrap-styled alert messages

Bootstrap includes dedicated message boxes for danger, warnings and information. If you were writing an ordinary web site, you would generate these using the following HTML markup:

<div class="alert alert-danger"
  <strong>Danger:</strong> This is a warning!

You can achieve this in R Markdown using knitr chunk hooks. Just add the following code to a chunk near the start of your .Rmd file.

   error = function(x, options) {
     paste('\n\n<div class="alert alert-danger">',
           gsub('##', '\n', gsub('^##\ Error', '**Error**', x)),
           '</div>', sep = '\n')
   warning = function(x, options) {
     paste('\n\n<div class="alert alert-warning">',
           gsub('##', '\n', gsub('^##\ Warning:', '**Warning**', x)),
           '</div>', sep = '\n')
   message = function(x, options) {
     paste('\n\n<div class="alert alert-info">',
           gsub('##', '\n', x),
           '</div>', sep = '\n')

And you’re done! For a full demonstration and further details, read this vignette.

To leave a comment for the author, please follow the link and comment on their blog: R on Tea & Stats. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)