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.
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.
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+
The xterm256 package by Romain Francoise allows this sort of thing in general on any console that understands xterm256 interrupts.
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.
On either Linux or Mac, you could try https://github.com/jalvesaq/colorout It doesn't work on Windows.
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: