问题
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).
回答1:
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:
来源:https://stackoverflow.com/questions/53188034/change-background-colour-of-knitrkable-headers