r - xtable 如何进行单元格着色

标签 r r-markdown pandoc

我在 .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"

最佳答案

您可以将相关的表条目包裹 n latex 代码( 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)
```

产生

enter image description here

关于r - xtable 如何进行单元格着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40895829/

相关文章:

r - 绘图功能不会在 lapply 期间抓取名称

r - 带有 Rmarkdown 文件的 pandoc-citeproc 错误 83

r - 使用 dplyr 管道将 for 循环的输出提取到 R 中的数据帧中

r - R 数据框中的十个最高列值

r - 渲染 PDF 时不在 for 循环中打印绘图(自 ggplot2 更新以来)

r - 通过 Rmarkdown 添加 MS Word 注释

r - 在 R markdown 中循环

haskell - 我可以在我的应用程序中自动嵌入 pandoc 的默认模板吗?

markdown - Pandoc Markdown : Omit text in PDF version but include in HTML version

r - 定义列组并用 dplyr 对每个组的所有第 i 列求和