Search code examples
rr-markdownknitrkablekableextra

Coloring cells in kableExtra based on value


I am working in R Markdown to create a pdf report, and have a table of probabilities like this:

x <- data.frame(a = c(0.1, 0.2, 0.4), b = c(0.3, 0.5, 0.7), c = c(0.8, 0.9, 0.5))

> x
    a   b   c
1 0.1 0.3 0.8
2 0.2 0.5 0.9
3 0.4 0.7 0.5

When knitting to pdf, the table is knit through kable, as such:

kable(x, format = 'latex', booktabs = T)

What is a simple way to have the cells colored by their probability value when knititng? I have seen similar questions, but none sufficiently answered my question.

My goal is to have an output that looks more-or-less like this:

Babou

Solution

  • You could try something like this in your knitr R chunk:

    suppressPackageStartupMessages(invisible(
      lapply(c("dplyr", "knitr", "kableExtra", "scales"),
               require, character.only = TRUE)))  
    
    x <- data.frame(a = c(0.1, 0.2, 0.4), 
               b = c(0.3, 0.5, 0.7), 
               c = c(0.8, 0.9, 0.5)) 
    xc <- seq(min(x), max(x), length.out = 10)
    pal <- seq_gradient_pal("#e9f7cb", "#1b7378")(xc)
    
    setSpec <- function(y){
      kableExtra::cell_spec(y, "latex", background = pal[cut(y, breaks=xc, include.lowest = TRUE)])
    }
    apply(x, 2, setSpec) %>% knitr::kable("latex", escape = FALSE, booktabs = TRUE, linesep = "")