更改knitr :: kable标头的背景颜色 [英] Change background colour of knitr::kable headers

查看:66
本文介绍了更改knitr :: kable标头的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更改用knitr :: kable打印的表格标题的背景颜色.我可以使用kableExtra::column_spec更改整个列的背景,但这不会影响标题行:

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")

想要的结果: kable输出,其中a列的标题为黄色背景(表的其余部分为白色背景).

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

推荐答案

您可以使用cell_spec进行此操作.例如,

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)

对我来说,这不会自动显示在RStudio中;您需要通过kableExtra函数对其进行管道传递.例如,此管道除了标记要显示的表外什么也不做.

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)

将显示

另一种方法是将包括标题的整个列设置为黄色,然后将非标题部分设置为继承的颜色.您是这样做的:

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")

此代码最终以凌乱的HTML开头,但间距看起来更好一些:

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

这篇关于更改knitr :: kable标头的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆