[英]color cells of pandoc table
我有这张表格,我想使用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"
如果要渲染为PDF,则您(或其他人的功能)必须使用LaTeX格式化表格。 尽管有很多有用的软件包和函数可以为您完成所有工作( knitr::kable
, xtable
, stargazer
),但是如果您需要细粒度的控制,则可能需要至少部分地自己编辑LaTeX。
一个合理的无痛选项是Hmisc::latex
,其将从data.frame创建表,并具有:(许多之间)的参数cellTexCmds
允许经由类似的尺寸的data.frame的矩阵传递定型为单个细胞。 file
参数为''
因此它不保存文件,而where = '!htbp'
因此该表将出现在文档中的正确位置。 要设置单元格背景色,您需要xcolor
或colortbl
LaTeX软件包,可以将其加载到YAML前端。
要消除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])
```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.