【问题标题】:how do you change the color of the cell in kable output table in knitr如何更改 knitr 中 kable 输出表中单元格的颜色
【发布时间】:2018-02-24 19:20:41
【问题描述】:

如果单元格的值大于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 输出表中的单元格着色?

【问题讨论】:

    标签: r knitr conditional-formatting kable


    【解决方案1】:

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

    【讨论】:

    • 这很棒,但因为最初的问题很复杂,所以答案也很复杂。您能否也提供一个一般性的答案,或者使用iris[1:5, ] %&gt;% kable %&gt;% kable_styling(fixed_thead = T) - 这会非常有帮助
    • 使用上面的例子,如果kable(df, "latex", escape = F) %&gt;% kable_styling(fixed_thead = T),我在Rmd 中什么也看不到,但是如果我将光标移到我希望看到某些东西的地方,它有点卡住,好像它识别出某些东西在那里但是我只是看不到它。我也试过kable(df, escape = F) %&gt;% kable_styling(fixed_thead = T) 渲染表格但没有颜色
    • @stevec 听起来您正在尝试用 html 制作表格?这可能不是那么明显,但这里提供的解决方案是针对乳胶的。您可以尝试在 kableextra 中使用 cell_spec,请参阅 this for details。我想这不是最干净的解决方案,但至少比编写原始 html/latex 更好。
    • @stevec 该示例使用dplyr,但最后cell_spec 仅根据编织环境编写原始html 或乳胶代码。没什么特别的
    【解决方案2】:

    不是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

    【讨论】:

      【解决方案3】:

      使用我的huxtable 包的另一种解决方案:

      library(huxtable)
      ht <- as_hux(df)
      ht <- set_background_color(ht, where(ht > 80), "red")
      ht
      

      【讨论】:

        猜你喜欢
        • 2019-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        • 2015-01-24
        • 2011-11-06
        • 1970-01-01
        相关资源
        最近更新 更多