7

I would like to change the colour of some output printed in R without importing external libraries. How can I do this?

I already know

print('this is black')

and

message('this is red')

But how can I do other colours? Green or blue, for example

Note

My question is similar to this except I am limited to using base R (no packages)

stevec
  • 41,291
  • 27
  • 223
  • 311
  • This depends on the terminal. For example, in R with a basic terminal on many systems there are no colors at all. What system and what R distribution (e.g. rstudio) are you using? – January Jul 14 '19 at 22:37
  • A work around could be to use plot `plot(0:1,0:1, type = 'n', axes = FALSE, ann = FALSE); text(0.5,0.5, 'test', col = 'orange')` – Tony Ladson Jul 14 '19 at 22:38
  • It’s not for me but for users of a script I’m working on. They’ll be using the most recent version of rstudio. I just need it to stand out more than black but not resemble an error (red) – stevec Jul 14 '19 at 22:39

1 Answers1

15

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

GreenLantern
  • 176
  • 1
  • 6
  • 3
    This is great. Can you explain how it works, or more specifically how I can get any particular colour? Is it using hex or something? (I've worked out something like `cat("\033[0;32mtest\033[0m\n")` gives green, but I still don't know how it does that – stevec Jul 15 '19 at 00:59
  • 4
    You can find a good explanation here: https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences – GreenLantern Jul 15 '19 at 08:13
  • 1
    Thanks for the link! I read it, plus some googling. Is it true to say you cannot produce all of the 16,777,216 colours that RGB can create? I.e. only [these](https://superuser.com/questions/270214/how-can-i-change-the-colors-of-my-xterm-using-ansi-escape-sequences) ones? Is there a way to get the other colours? E.g. `#FF6600` – stevec Jul 15 '19 at 09:32
  • 1
    I'm sorry, but I don't know if there are other ways to get other colors. If you find other methods, write them here so I can learn them too. – GreenLantern Jul 15 '19 at 09:42