rcolorskablekableextra

Color values beyond a threshold in a table in R


If I have the following table for the mtcars dataset:

knitr::kable(mtcars) %>%  
   kableExtra::kable_styling(c("bordered","condensed"), font_size = 15,full_width = T)

How can I color only the values (not cells) greater than, for example, 5 on that table?

Thanks in advance!


Solution

  • You can use cell_spec with kable(escape = FALSE) to predefine all cells' colors:

    library(dplyr)
    library(knitr)
    library(kableExtra)
    
    df <- mtcars
    df %>% 
      mutate(across(everything(), ~ cell_spec(.x, color = ifelse(.x > 5, "red", "black")))) %>% 
      kable(escape = FALSE) %>%  
      kable_styling(c("bordered","condensed"), font_size = 15, full_width = T)
    

    enter image description here