本文介绍了xtable 如何进行单元格着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 table = data.frame(category = c("A","B","C"), groupA = c(.2,.3,.5), groupB= c(.6,.7,.9))桌子pandoc.table(table,split.table = Inf,keep.line.breaks = TRUE)-----------------------------类别组A组B---------- -------- --------0.2 0.6乙 0.3 0.70.5 0.9-----------------------------

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

>0 and 
解决方案

可以将相关表条目包裹 n 乳胶代码 (

I have this table in a .RMD file and I would like to render in PDF with conditional formatting. Currently I am using pandoc. How can this be done with 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   
----------------------------

How can I color the cells of the "groupA" and "groupB" columns with conditional formatting like:

>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"
解决方案

You can wrap the relevant table entries n latex code (from here), and then sanitize the xtable results.

Example:

---
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)
```

which produces

这篇关于xtable 如何进行单元格着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 09:49