2017-09-15 74 views
2

我需要着色单元,如果单元格的值大于80。例如更大kable输出表中的单元格的颜色,给这个数据帧称为DF:你如何改变在knitr

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表,它不会打印出来。任何想法如何在彩色输出表中对单元格着色?

回答

3

不是knitr解决方案...
您可以修改特定的细胞DT::datatableformatStyle。它有更多的显示选项,我正在使用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

事实上,你甚至不需要DTkableExtra如果你需要的是单元格的颜色。用我的huxtable包装物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

另一种解决方案:

library(huxtable) 
ht <- as_hux(df) 
ht <- set_background_color(ht, where(ht > 80), "red") 
ht 
然而,由于 kableExtra作者,我虽然建议包