如何在knitr的kable输出表中更改单元格的颜色 [英] how do you change the color of the cell in kable output table in knitr
问题描述
如果单元格的值大于80,则需要为单元格着色.例如,给定名为df的数据帧:
I need to color the cell if the value of the cell is greater than 80. For example, given this data frame called 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,2] should be in red color. I was able to change the color of the text by something like this using xtable:
df[, 2] = ifelse(df[, 2] > 80, paste("\\color{red}{", round(df[, 2], 2), "}"), round(df[, 2], 2))
如果我这样做并用电缆打印出桌子,它就不会打印出来.有什么想法可以给kable输出表中的单元格上色吗?
If I do this and print out the table with kable, it wont print out. Any ideas how can I color the cell in kable output table?
推荐答案
实际上,如果您只需要该单元格的颜色,则甚至不需要DT
或kableExtra
.但是,作为kableExtra
的作者,我确实建议使用该程序包:P
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)
这篇关于如何在knitr的kable输出表中更改单元格的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!