【问题标题】:color cells of pandoc tablepandoc表的颜色单元格
【发布时间】:2016-11-29 22:48:05
【问题描述】:

我有这张表格,我想在 RMD 文件中使用 PANDOC 以 PDF 格式呈现

 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"

【问题讨论】:

  • 渲染成 HTML 或 PDF?如果是前者,请查看formattable
  • 我不能使用formattable,因为它是PDF

标签: r pdf knitr r-markdown


【解决方案1】:

如果您要渲染为 PDF,您(或其他人的函数)必须使用 LaTeX 格式化您的表格。虽然有很多有用的包和功能可以为您完成所有工作(knitr::kablextablestargazer),但如果您需要细粒度的控制,您可能需要自己编辑 LaTeX,至少在部分。

一个相当轻松的选项是Hmisc::latex,它将从 data.frame 创建表,并有一个参数(在许多参数中)cellTexCmds 允许通过与数据相似维度的矩阵传递单个单元格的样式。框架。将file 参数设置为'',因此它不保存文件,where = '!htbp' 使表格出现在文档中的正确位置。要设置单元格背景颜色,您需要 xcolorcolortbl LaTeX 包,它们可以在 YAML frontmatter 中加载。

要消除 LaTeX 注释,捕获输出、子集和打印,或者只使用 .Rnw 而不是 .Rmd。

---
title: "Conditional Formatting"
header-includes:
   - \usepackage[table]{xcolor}
output:
  pdf_document: default
---


```{r}
df <- data.frame(category = c("A","B","C"), 
                 groupA = c(.2,.3,.5), 
                 groupB= c(.6,.7,.9))

df.format = matrix('', nrow = nrow(df), ncol = ncol(df))

df.format[, -1] <- paste0('cellcolor{', 
                          sapply(df[-1], function(x){
                              cut(x, breaks = c(0, seq(.2, .8, by = .1), 1), 
                                  labels = c('green', 'red', 'blue', 'orange', 
                                             'yellow', 'black', 'brown', 'white'))}),
                          '}')

df.format
```

```{r table, results='asis'}
cat(capture.output(
    Hmisc::latex(df, file = '', cellTexCmds = df.format, where = "!htbp")
    )[-1])
```

【讨论】:

  • 我无法显示此“%latex.default(df, file = "", cellTexCmds = df.format, where = "!htbp")%"。你知道使用 rmd 的其他选择吗?
  • latex 旨在写入文件,因此您可以写入文件并使用readLines 将其导入,跳过第一行。但是,由于无法解释的原因,试图让它写一个文件让我挂起 R,所以一个更简单的解决方法是捕获输出、子集和打印:cat(capture.output( Hmisc::latex(df, file = '', cellTexCmds = df.format, where = "!htbp"))[-1])
  • \usepackage[table]{xcolor} 导致我的(非 R)pandoc 出现问题,因为 xcolor 已经加载到 default.latex 模板中。所以,我尝试在header-includes 中使用\PassOptionsToPackage{table}{xcolor},虽然没有导致错误,但没有效果,因为default.latex 再次使用\PassOptionsToPackage 和xcolor。我的解决方案是复制 default.latex 模板并对其进行修改,使用--template= 在 pandoc 命令上指向它。
猜你喜欢
  • 1970-01-01
  • 2020-07-02
  • 2015-01-24
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 2018-10-05
  • 2019-11-16
相关资源
最近更新 更多