'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 1:[1]

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

Solution 2:[2]

I think you need to manually work through the cells setting the colour.

There is a reason they don't use red-green as a scale. 1:12 men can't tell what colour it is. Just because excel let's you do it, doesn't mean you should!

Flextable may offer an easier way

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdur Rohman
Solution 2 CALUM Polwart