2017-09-15 50 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作者,我雖然建議包