Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

r - how can xtable do cell coloring

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...