rr-markdownknitr

knitr - R markdown Changing font size and/or colour of message()/print() output


Is there a way to adjust font size and/or colour of message() or print() output when compiled with knitr?

Example:

a <- sum(rnorm(10))

trigger <-ifelse(a>0, TRUE, FALSE)

if (trigger==TRUE) message("positive") else message("negative")

I would like such a message being displayed large(er) and in distinctive colours in the resulting html document. Any ideas?


Solution

  • One way could be to use knit_hooks$set on the message function and change the message style depending on it's content. This is how to do this for the HTML output format.

    out

    ---
    title: "warningMessage"
    output: html_document
    date: "2025-06-27"
    ---
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    library(knitr)
    
    knit_hooks$set(message = function(x, options) {
      if (grepl("positive", x)) {
        paste0('<div style="color: green; font-size: 20px; font-weight: bold; margin: 10px 0;">', x, '</div>')
      } else if (grepl("negative", x)) {
        paste0('<div style="color: red; font-size: 20px; font-weight: bold; margin: 10px 0;">', x, '</div>')
      } else {
        paste0('<div class="message">', x, '</div>')
      }
    })
    ```
    ```{r message}
    if (5>0) message("positive") else message("negative")
    if (-5>0) message("positive") else message("negative")
    ```