如何在rmarkdown pdf输出中为单元格上色 [英] how do you color the cell in rmarkdown pdf output

查看:157
本文介绍了如何在rmarkdown pdf输出中为单元格上色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使cellcolor在rmarkdown中工作:

I cannot get cellcolor to work in rmarkdown:

---
header-includes:
   -  \usepackage{colortbl} 
   -  \usepackage{color} 

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

我不断收到此错误:

! Undefined control sequence.
l.155 1 & A & \cellcolor

任何想法都需要cellcolor起作用?

Any ideas what does cellcolor needs to work?

推荐答案

更新

当包含\usepackage[dvipsnames]{xcolor}时,OP的示例对我有用.有关另一种方法,请参见下文.

Update

The OP's example works for me when including \usepackage[dvipsnames]{xcolor} instead. For another approach see below.

这是使用非常方便的condformat软件包的另一种方法.这样,您不必手工包含任何TeX软件包,也不必担心转义特殊字符等.

Here is another approach using the very handy condformat package. This way you don't have to include any TeX packages by hand and don't have to worry about escaping special characters etc.

我们基本上创建一个condformat_tbl对象,并为每列添加两个格式规则.

We basically create a condformat_tbl object and add two formatting rules for each column.

---
output:
    pdf_document
---

```{r, include = F}
library(condformat)
cols        <- c('green', 'red', 'blue', 'orange', 
                 'yellow', 'purple', 'brown', 'white')
names(cols) <- cols # important for the colours arg in rule_fill_discrete
                    # since it matches the result of 'expression' with the names of the 'colours' vector

f   <- function(x) cut(x, c(0, seq(.2, .8, .1), Inf), labels = cols,
                       include.lowest = FALSE, right = TRUE)
tab <- data.frame(category = c('A', 'B', 'C'), 
                  groupA = c(.2, .3, .5), 
                  groupB = c(.6, .7, .9))
```


```{r, results = 'asis', echo = F}
condformat(tab) + 
  rule_fill_discrete(groupA, expression = f(groupA), colours = cols) +
  rule_fill_discrete(groupB, expression = f(groupB), colours = cols) 
```

请注意,rule_fill_discrete中colors参数的值是键-值对的向量.键是表达式的可能结果.

Notice, that the value for the colours argument in rule_fill_discrete is vector of key-value pairs. The keys are the possible results of the expression.

这就是你得到的:

这篇关于如何在rmarkdown pdf输出中为单元格上色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆