how do you change the color of the cell in kable output table in knitr

巧了我就是萌 提交于 2019-12-01 10:36:39

In fact, you don't even need DT or kableExtra if all you need is the color of that cell. However, as the author of kableExtra, I do recommend that package though :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)

Not a knitr solution...
You can modify specific cells with DT::datatable formatStyle. It has more display options and I'm using list(dom = "t") to turn them off and ordering = FALSE to remove sorting options from the top off the table.

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

If you prefer kable way then you should try kableExtra. They have option to change background for specified rows.

Another solution using my huxtable package:

library(huxtable)
ht <- as_hux(df)
ht <- set_background_color(ht, where(ht > 80), "red")
ht
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!