Change background colour of knitr::kable headers

北战南征 提交于 2021-02-08 06:13:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!