Mister Palmer Mister Palmer - 2 months ago 15
R Question

R: Color cells in a table based on the given value

i'm new in programming with R and I have the following problem:

I have a table with the numbers 1-10. It looks like this:

My Table

Now I want to fill the cells with a different color for each integer.
For Example all cells with the value 1 should be red, 2 black.. and so on.
Have you any suggestions how to achieve this?
Thanks a lot.

Answer

There do exist packages that will do this. The package that currently has the most direct interface is probably condformat using the condformat::rule_file_discrete function. I don't have a working example, unfortunately, because I condformat required rJava, which doesn't get along well with my system.

The pixiedust package (full disclosure, I am the author) can accomplish this, but it isn't very direct at the moment.

library(pixiedust)
library(scales)
library(magrittr)

# Make the table (as a matrix, but a data frame would work as well)
set.seed(pi)
X <- matrix(sample(1:10, 
                   size = 100, 
                   replace = TRUE),
            nrow = 10)

# Define 10 colors
background <- hue_pal()(10) %>%
  setNames(1:10)

show_col(background)


# Convert X to a dust object
X_dust <- dust(X)

# Apply the background colors
for (i in sort(unique(as.vector(X)))){
  X_dust <- 
    sprinkle(X_dust,
             rows = X_dust$body$row[X_dust$body$value == i],
             cols = X_dust$body$col[X_dust$body$value == i],
             bg = background[i],
             fixed = TRUE)
}

# Print the HTML code
X_dust %>%
  sprinkle_print_method("html")

I am currently developing code to do this with just a few lines of code, but that feature isn't quite ready for release yet.