【问题标题】:how can xtable do cell coloringxtable如何进行单元格着色
【发布时间】:2023-03-26 19:20:01
【问题描述】:

我在 .RMD 文件中有这个表格,我想用条件格式呈现 PDF。目前我正在使用 pandoc。 xtable 如何做到这一点?

 table = data.frame(category = c("A","B","C"), groupA = c(.2,.3,.5), groupB= c(.6,.7,.9))
 table
 pandoc.table(table,split.table = Inf,keep.line.breaks = TRUE)

----------------------------
 category   groupA   groupB 
---------- -------- --------
    A        0.2      0.6   

    B        0.3      0.7   

    C        0.5      0.9   
----------------------------

如何使用条件格式为“groupA”和“groupB”列的单元格着色,例如:

>0 and <= .2    = "green"
>.2 and <= .3    = "red"
>.3 and <= .4    = "blue"
>.4 and <= .5     = "orange"
>.5 and <= .6     = "yellow"
>.6 and <= .7     = "black"
>.7 and <= .8     = "brown"
>.8  = "white"

【问题讨论】:

    标签: r r-markdown pandoc


    【解决方案1】:

    您可以用乳胶代码 (from here) 包装相关的表条目,然后清理 xtable 结果。

    例子:

    ---
    header-includes:
       - \usepackage{xcolor, colortbl}
    output:
        pdf_document
    ---
    
    ```{r, results="asis"}
    
    library(xtable)
    # Your data
    tab = data.frame(category = c("A","B","C"), groupA = c(.2,.3,.5), groupB= c(.6,.7,.9))
    
    # Function to cut your data, and assign colour to each range
    f <- function(x) cut(x, c(0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, Inf), 
                          labels=c("green", "red", "blue", "orange", "yellow", "purple", "brown", "white"),
                          include.lowest = FALSE, right = TRUE)
    
    # Apply function to columns: this overwrites your data
    tab[c("groupA", "groupB")] <- lapply(tab[c("groupA", "groupB")], function(x)
                                                paste0("\\cellcolor{", f(x), "}", x))
    # Sanitise output 
    print(xtable(tab), sanitize.text.function = identity)
    ```
    

    产生

    【讨论】:

    • 我收到了这个错误!额外对齐选项卡已更改为 \cr。 \endtemplate
    • @user3022875 ;我刚刚将答案中的代码复制并粘贴到一个新的 .Rmd 文件中,它按预期运行。您是否添加了任何内容,例如更改了列数或对齐?
    【解决方案2】:

    你可以看看格式化包

    例如

    library(formattable)
    
    formattable(table, 
                 list(groupA = color_tile("white", "orange"))
               )
    

    https://github.com/renkun-ken/formattable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-23
      • 2013-01-09
      • 2011-08-19
      • 2016-05-08
      • 1970-01-01
      • 2017-11-04
      • 2015-09-10
      相关资源
      最近更新 更多