Is there a way to output text to the R console in color

32.2k views Asked by At

I am writing a script and I want to output text messages to the console with different colors depending on conditions. For example: RED for errors and BLUE for warnings, etc.

I am using RStudio.

6

There are 6 answers

0
Quinten On BEST ANSWER

Another option could be using the insight package with the print_color function. You could also make the text bold or italic. Here is some reproducible code:

library(insight)
print_color("ERROR", "red")
print_color("WARNINGS", "blue")

Output RStudio:

enter image description here

3
Gavin Simpson On

The xterm256 package by Romain Francoise allows this sort of thing in general on any console that understands xterm256 interrupts.

0
Aquino On

On either Linux or Mac, you could try https://github.com/jalvesaq/colorout It doesn't work on Windows.

0
Pedro_S On

Actually, there IS a way without using R packages (Crayon and cli):

Use cat, paste0 and some ANSI hell to do it:

txt<-"rainbow"
for(col in 29:47){ cat(paste0("\033[0;", col, "m",txt,"\033[0m","\n"))}

You will need to do a bigger function, since cat is not very flexible, but this works well.

Obs: This solution was observed by a colleague, which is a perl stan.

13
krlmlr On

Check out the new crayon package:

library(crayon)
cat(blue("Hello", "world!\n"))

More info on the GitHub page.

Works in RStudio 1.2.360+

0
Joseph Crispell On

Late to the game but building on @Pedro_S's answer here's an example of how could write functions to use ANSI colours to print coloured text based on plain text input of colours ("red", "green", etc.):

#' Convert plain text colour to ANSI code
#'
#' @param colour colour in plain text ("red", "green", etc.) to convert to ANSI
#'
#' @return string representing provided colour as ANSI encoding
#'
#' @examples
#' colour_to_ansi("red") # gives: "\033[31m"
colour_to_ansi <- function(colour) {
  # Note ANSI colour codes
  colour_codes <- list(
    "black" = 30,
    "red" = 31,
    "green" = 32,
    "yellow" = 33,
    "blue" = 34,
    "magenta" = 35,
    "cyan" = 36,
    "white" = 37
  )

  # Check colour provided in codes above
  if (colour %in% names(colour_codes) == FALSE) {
    stop(
      paste0(
        "Colour provided (", colour, ") can't be converted to ANSI. ",
        "Must be one of: \n", paste(names(colour_codes), collapse = ",")
      )
    )
  }

  # Create ANSI version of colour
  ansi_colour <- paste0("\033[", colour_codes[[colour]], "m")

  return(ansi_colour)
}

#' Print (cat) progress text as coloured text
#'
#' @param text string to print using cat()
#' @param colour plain text colour ("red", "green", etc.). Defaults to "green"
#'
#' @examples
#' coloured_print("This is a test", colour = "blue")
coloured_print <- function(text, colour = "green") {
  cat(colour_to_ansi(colour), text, "\033[0m\n")
}