如何在knitr的kable输出表中更改单元格的颜色 [英] how do you change the color of the cell in kable output table in knitr

查看:257
本文介绍了如何在knitr的kable输出表中更改单元格的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果单元格的值大于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?

推荐答案

实际上,如果您只需要该单元格的颜色,则甚至不需要DTkableExtra.但是,作为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆