Search code examples
rr-markdownkablexaringan

KableExtra conditional tables in R


I am working on replicating in a Rmarkdown a report I made in Excel.

In some of the results I have tables with conditional columns with color formatting, from red to green (red for the lowest data and green for the highest data).

Here an example:

example

I have searched but the closest I found was to do this:

df %>%
  kbl() %>%
  kable_paper(full_width = F) %>%
  column_spec(2, color = "white",
              background = spec_color(df$B,begin=0, end = 1,option='D'))

Result

My problem now is that the spec_color() argument only has 5 color maps and none of them go from red to green.

Does anyone know how I could add a colormap for the conditional formatting just like the one I used in Excel?

I am new using Rmarkdowns, thanks.


Solution

  • One way of coloring the columns is by using data_color from {gt} package. You can specify the colors in various ways, including manually supplying the names of your desired colors available in grDevices::colors(). You can also specify the domain with the range of the values in the targeted column.

    For example:

    library(tidyverse)
    library(gt)
    
    iris[45:55,c(1,5)] %>% gt() %>%
        data_color(columns = Sepal.Length, colors = scales::col_numeric(
            palette = c("tomato","yellow", "green4"), 
            domain = range(Sepal.Length)))
    

    which results in the following colors

    enter image description here