Coloring background in HTML table with kable / kableExtra by row values instead of column values

I'm trying to change the coloring of the background so the coloring is based on row values1 and values2 instead of column, but I'm not sure about the best way to do this. Does anyone have a good idea for the best way to do this?


library(tidyverse)
library(kableExtra)

df <- tibble(variable = letters[1:6], value1 = c(1:3, NA, 2, NA), value2 = c(3:1, NA, NA, 2)) 


kableExtra::kbl(df, format = "html", escape = FALSE) %>%
  kableExtra::column_spec(2, color = "white",
                          background =  kableExtra::spec_color(df$value1, end = 0.7)) %>%
  kableExtra::column_spec(3, color = "white",
                          background =  kableExtra::spec_color(df$value2, end = 0.7))


The function cell_spec came to the rescue.

df <- tibble(variable = letters[1:6], value1 = c(1:3, NA, 2, NA), value2 = c(3:1, NA, NA, 2)) 

gc_cell_spec_row <- function(x){
  
  if(all(is.na(x))){
    x <- kableExtra::cell_spec(x = x, format = "html", color = "white",
                               background = "#BBBBBB")
  } else {
    x <- kableExtra::cell_spec(x = x, format = "html", color = "white",
                               background = kableExtra::spec_color(x, end = 0.7))
  }
  x
}


df2 <- 
  df %>% 
  pivot_longer(value1:value2) %>% 
  group_by(variable) %>%
  mutate(value = gc_cell_spec_row(value))

df2 %>% 
  pivot_wider(names_from = name, 
              values_from = value) %>% 
  kableExtra::kbl(., "html", escape = FALSE)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.