Home > Software design >  Conditionally color rows in table KableExtra()
Conditionally color rows in table KableExtra()

Time:12-10

I would like to use kableExtra to conditionally format the table with data.

Let's use an iris dataset as a reprex. Also, let's assume, that I would like to color the rows according to the species.

This is the code I was trying to play with - an example from the documentation:

iris %>% mutate(Species = cell_spec(Species, color = spec_color(1:10, option = "A"), link = "#",tooltip = paste0("Sepal Length: ", Sepal.Length))) %>% kable("html", escape = F, align = "c") %>% kable_styling("condensed", full_width = F)

However it does not color rows according to species. Can anyone help?

CodePudding user response:

Not sure spec_color is the right function, from the documentation: "spec_color would map a continuous variable to any viridis color palettes.";

You are looking to map a discrete variable to all variables.

This might be an approach:

(Note: If you want to colour the background substitute "background" for "color".)

Revised to include OP's comment to control order of colours.

library(kableExtra)
library(dplyr)

# make a minimal data frame:

iris1 <- 
  iris %>%
  group_by(Species) %>% 
  slice_head(n = 4) %>% 
  ungroup()

 iris1 %>% 
  mutate(across(everything(), ~cell_spec(.x, color = factor(iris1$Species, labels =  c("red", "green", "blue")),
                                         link = "#",
                                         tooltip = paste0("Sepal Length: ", Sepal.Length)))) %>%
   kable("html", escape = F, align = "c") %>% 
   kable_styling("condensed", full_width = F)

Which results in:

enter image description here

To control the order of colours, manipulate the factor levels and labels as required, for example:

   iris1 %>% 
  mutate(across(everything(), ~cell_spec(.x, color = factor(iris1$Species, 
                                                            levels = c("versicolor", "setosa", "virginica"),
                                                            labels =  c("red", "green", "blue")),
                                         link = "#",
                                         tooltip = paste0("Sepal Length: ", Sepal.Length)))) %>% 
   kable("html", escape = F, align = "c") %>% 
   kable_styling("condensed", full_width = F)

enter image description here

  • Related