66

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.

smci
  • 32,567
  • 20
  • 113
  • 146
notuo
  • 1,091
  • 2
  • 9
  • 15

5 Answers5

59

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+

adilapapaya
  • 4,765
  • 3
  • 25
  • 26
krlmlr
  • 25,056
  • 14
  • 120
  • 217
3

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

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • This looks promising but doesn't work in R Studio. Too bad for me. Thanks for the tip – notuo May 29 '12 at 16:59
  • is there any further update on this? Or we still do not have any R package that outputs coloured text on Rstudio console or alternatively on the plot or view pane of Rstudio. – Lazarus Thurston Sep 20 '17 at 14:28
  • 4
    Crayon works in RStudio now for me (Linux Mint 18.2, R 3.4.3, Crayon 1.3.4, RStudio 1.2.360). – CoderGuy123 Mar 05 '18 at 15:53
2

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.

Pedro_S
  • 21
  • 2
1

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

Aquino
  • 136
  • 4
1

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

Quinten
  • 35,235
  • 5
  • 20
  • 53