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.