Search code examples
rkablekableextra

Kable conditional coloring using row_spec


I'm trying to color cells in each row based on a condition using kable. I saw a few examples of column_spec and cell_spec because it's still a bit manual since I'm interested in conditional coloring by row. Here's an example of column_spec, and wondering if this can be down with row_spec or similar that's more efficient than column_spec or cell_spec?

mtcars[1:8, 1:8] %>%
      arrange(wt) %>%
      kbl(booktabs = T, linesep = "") %>% 
      kable_paper(full_width = F) %>%
      column_spec(6, color = "white", background = ifelse(mtcars[1:8,1:8]$drat > 3, "red", "green"))

enter image description here

However, the conditional formatting I'm interested in is coloring, say Mazda RX4 row has any values >10 then red. This is just example data so context isn't relevant here. Thanks!


Solution

  • We can use some dplyr operations before piping into Kable.

    library(tidyverse)
    library(knit)
    library(kableExtra)
    
    mtcars_kbl <- mtcars[1:8, 1:8] 
    
    mtcars_kbl$car = row.names(mtcars_kbl)
    row.names(mtcars_kbl) <- NULL
    
    mtcars_kbl %>% arrange(wt) %>% 
      relocate(car) %>% 
      mutate(
        across(1:8, 
               ~ cell_spec(.x, 
                           color = ifelse(car == "Mazda RX4" & .x > 10, "white", "black"), 
                           background = ifelse(car == "Mazda RX4" & .x > 10, "red", "white")
                           )
               )
        ) %>% 
      kable(booktabs = T, linesep = "", format = "html", escape = F) %>% 
      kable_paper(full_width = F)
    

    kable_cell_spec