Pretty errors, warnings and messages in R Markdown
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:
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 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! </div>
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.
knitr::knit_hooks$set( 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.
R-bloggers.com 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.