1

I'm generating 8 individual vectors of 18 random numbers, and I want to color-code all the numbers under 11 red and everything else can stay black.

trial1 <- sample(0:99, 18, repeat = TRUE) performed 8 times, changing the trial number each time.

 if (trial1<=11) {
     print(col ="red")
 } else {
     print(col = "black")

but this throws an error message and I don't know where I messed up. I'm trying to display all 18 numbers as either red or black. Is this possible, and how do I do it?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
user14
  • 11
  • 1
  • 2
    Are you talking about printing to your console, or somewhere else (e.g., in an Rmarkdown document). If you're talking about printing in your R console, then the `crayon` package has you covered, [see this dupe](https://stackoverflow.com/q/10802806/903061). – Gregor Thomas Oct 27 '20 at 15:41
  • 3
    The error is because `print` needs an argument to print that is either the first unnamed argument or named `x`. `print(col = "black")` doesn't tell it what to print. (And also, there is no `col` argument, but `print` is willing to let that slide and ignore it, as long as you give it something to print...). You can always check the help page `?print` to see what arguments a function takes. – Gregor Thomas Oct 27 '20 at 15:43

2 Answers2

0

As was said in the comments, you can't do print(col = ...). However, you can store it in a vector:

> trial1 <- sample(0:99, 18)

> col1 <- ifelse(trial1 <= 11, "red", "black")

> trial1
 [1] 41 77 81 87 84  3 32 14 86 20 25 37 67 45 17 98 31 53

> col1
 [1] "black" "black" "black" "black" "black" "red"   "black" "black" "black" "black" "black" "black"
[13] "black" "black" "black" "black" "black" "black"

Also, I don't know what you mean with repeat = TRUE. Maybe you mean replace = TRUE.

Érico Patto
  • 1,015
  • 4
  • 18
0

You can use the ‘crayon’ package in combination with R’s ifelse:

trial1 = sample(0 : 99, 18L, replace = TRUE)

cat(toString(ifelse(trial1 <= 11, crayon::red(trial1), trial1)), '\n')

‘crayon’ itself does no printing, it generates ANSI escape sequences that many terminals interpret as colour commands. When passed to cat, this generates colourful output (if the terminal supports it).

Note that you need a command such as cat, message or writeLines here — print doesn’t work. The reason is that, contrary to what its name suggests, the print function doesn’t actually print proper output. Instead, it creates (and prints) a debug representation of R objects. That’s why it always prints indices on the left next to vectors, and why it prints strings surrounded by "…".

If you want to produce output in a script, print is almost always the wrong choice. Instead, you’d use one of the functions mentioned above.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214