我将此表保存在.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乳胶代码(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)
```
产生