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")
Wanted outcome:
A kable
output where the header of column a
has a yellow background (and the rest of the table a white background).
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
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:
kable(data.frame(a = 1, b = 2)) %>%
row_spec(0, background = "yellow")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With