如果单元格的值大于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输出表中为单元格着色?
答案 0 :(得分:7)
事实上,如果您需要的只是该单元格的颜色,您甚至不需要DT
或kableExtra
。但是,作为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)
答案 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"))
如果您更喜欢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