如何在knitr中更改kable输出表中单元格的颜色

时间:2017-09-15 14:45:43

标签: r knitr conditional-formatting kable

如果单元格的值大于80,我需要为单元格着色。例如,给定此数据框称为df:

dput(df)

structure(list(Server = structure(1:2, .Label = c("Server1", 
"Server2"), class = "factor"), CPU = c(79.17, 93), UsedMemPercent = c(16.66, 
18.95)), .Names = c("Server", "CPU", "UsedMemPercent"), row.names = c(NA, 
-2L), class = "data.frame")

df [2,2]应为红色。我可以使用xtable:

通过类似的方式更改文本的颜色
df[, 2] = ifelse(df[, 2] > 80, paste("\\color{red}{", round(df[, 2], 2), "}"), round(df[, 2], 2))

如果我这样做并用kable打印出桌子,它就不会打印出来。任何想法如何在kable输出表中为单元格着色?

3 个答案:

答案 0 :(得分:7)

事实上,如果您需要的只是该单元格的颜色,您甚至不需要DTkableExtra。但是,作为kableExtra的作者,我确实推荐这个包:P

# What u have now
df <-structure(list(Server =structure(1:2, .Label =c("Server1","Server2"), class = "factor"), CPU =c(79.17, 93), UsedMemPercent =c(16.66,18.95)), .Names =c("Server", "CPU", "UsedMemPercent"), row.names =c(NA,-2L), class = "data.frame")
df[, 2] =ifelse(df[, 2]>80,paste("\\color{red}{",round(df[, 2], 2), "}"),round(df[, 2], 2))
# What you need
kable(df, "latex", escape = F)

enter image description here

答案 1 :(得分:4)

不是knitr解决方案......
您可以使用DT::datatable formatStyle修改特定单元格。它有更多显示选项,我使用list(dom = "t")将其关闭,ordering = FALSE从表格顶部删除排序选项。

library(magrittr)
library(DT)
df %>%
    datatable(options = list(dom = "t", ordering = FALSE), 
              rownames = FALSE,
              width = 10) %>%
    formatStyle("CPU", backgroundColor = styleEqual(93, "red"))

enter image description here

如果您更喜欢kable方式,那么您应该尝试kableExtra。他们可以选择change background for specified rows

答案 2 :(得分:2)

使用我的huxtable包的另一种解决方案:

library(huxtable)
ht <- as_hux(df)
ht <- set_background_color(ht, where(ht > 80), "red")
ht
相关问题