Search code examples
rr-markdownknitrkablekableextra

Change background colour of knitr::kable headers


I need to change the background colour of the headers of a table printed with knitr::kable. I can use kableExtra::column_spec to change the background of a whole column, but it doesn't affect the header row:

library(knitr)
library(kableExtra)

kable(data.frame(a = 1, b = 2)) %>% 
  column_spec(1, background = "yellow")

enter image description here

Wanted outcome: A kable output where the header of column a has a yellow background (and the rest of the table a white background).

enter image description here


Solution

  • You can do this using cell_spec. For example,

    df <- data.frame(a = 1, b = 2)
    names(df)[1] <- cell_spec(names(df)[1], background = "yellow")
    kable(df, escape = FALSE)
    

    This doesn't display automatically in RStudio for me; you need to pipe it through a kableExtra function to do that. For example, this pipe does nothing except to mark the table to display.

    kable(df, escape = FALSE) %>% column_spec(1)
    

    will display

    screenshot

    Another way to do it is to set the whole column including the header to yellow, then set the non-header part to the inherited colour. You do that like this:

    kable(df) %>% 
      column_spec(1, background = "yellow", include_thead = TRUE) %>%
      column_spec(1, background = "inherit")
    

    This one ends up with messy HTML, but the spacing looks a bit better:

    screenshot 2