Change background colour of knitr::kable headers
Asked Answered
F

2

5

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

Frondescence answered 7/11, 2018 at 10:52 Comment(0)
P
7

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

Plane answered 7/11, 2018 at 12:25 Comment(0)
R
7
kable(data.frame(a = 1, b = 2)) %>% 
  row_spec(0, background = "yellow")
Ribonuclease answered 11/3, 2021 at 19:37 Comment(1)
This makes all of the column names yellow. OP wants only specific column as yellow.Body

© 2022 - 2024 — McMap. All rights reserved.