How to Output Text to the R Console in Color

How to change the colour of the printed output in base R?

You can try use this:

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

or if you want other function interesting i find this

https://github.com/r-lib/testthat/blob/717b02164def5c1f027d3a20b889dae35428b6d7/R/colour-text.r

R: a cat of many colors

See this file from the testthat package for an excellent example on how to create colored text:
https://github.com/hadley/testthat/blob/717b02164def5c1f027d3a20b889dae35428b6d7/R/colour-text.r

You can just use this colourise function to add color to your text. The file also has a bunch of predefined colors.

EDIT

There is now an R package for ANSI colors on CRAN, it is called crayon. Disclaimer: I am the package author. http://cran.r-project.org/web/packages/crayon/index.html https://github.com/gaborcsardi/crayon

How to print to console in color?

Define color like this:

W  = '\033[0m'  # white (normal)
R = '\033[31m' # red
G = '\033[32m' # green
O = '\033[33m' # orange
B = '\033[34m' # blue
P = '\033[35m' # purple

print(R+"hello how are you"+W)

Demo:
Demo

see all color codes here:Color Codes

customise R help files - font colouring

This is possible, but a little involved. You'll need your own css file defined to do it, though it would be possible to create a function that writes appropriate css.

As a proof of concept, I have used a copy of the "R.css" file defined inside every package's "/html" folder, and just changed the h2 color to red, with the file saved locally as "my.css".

Anyway, once you have the css file, this function will show the appropriate help file with the appropriate styling in your R viewer window:

help_css <- function(func, css_file)
{
pack <- sub("^.*:(.*)>$", "\\1", capture.output(environment(func)))
func <- deparse(substitute(func))

x <- readLines(paste0(find.package(pack), "/html/", func, ".html"))
x[3] <- paste("<style>",
paste(readLines(css_file), collapse = "\n"),
"</style>")
writeLines(x, file.path(tempdir(), "test.html"))

myViewer <- getOption("viewer")
myViewer(file.path(tempdir(), "test.html"))
}

So, for example, if I do:

help_css(lm, "my.css")

I get:

Sample Image



Related Topics



Leave a reply



Submit