0

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.

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
  • it's unclear what you're looking for. you cannot "color" in tables in R. Do you want this done in an html table, an excel table, some other table format? – Cyrus Mohammadian Sep 14 '16 at 10:33
  • so there is no package to plot a table in the way i want? – Mister Palmer Sep 14 '16 at 10:40
  • Please explain in what format you want the table to be printed. Here are a few tips on how to make a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) worthy of its name. – Roman Luštrik Sep 14 '16 at 10:45

1 Answers1

0

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.

Benjamin
  • 16,897
  • 6
  • 45
  • 65