【问题标题】:how do you color the cell in rmarkdown pdf output你如何为 rmarkdown pdf 输出中的单元格着色
【发布时间】:2017-12-31 21:19:04
【问题描述】:

我无法让 cellcolor 在 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 需要什么工作?

【问题讨论】:

标签: r knitr r-markdown


【解决方案1】:

更新

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

替代方法

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


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

---
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 中颜色参数的值是键值对向量。键是表达式的可能结果。

这就是你得到的:

【讨论】:

  • 我仍然看到这个错误:!未定义的控制序列。 l.91 A & \cellcolor
  • 试试devtools::install_github('zeehio/condformat')
  • 我确实使用 install.packages("condformat") 安装了包
  • 我能补充的是它与RStudio 1.0.143R 3.4.1 condformat 0.6.0.9000knitr 1.16一起工作
  • @MartinSchmelzer 确实,这解决了问题。 (至少对于 RStudio 和 rmarkdown::render 中的“编织”按钮。虽然不是 knit2pdf,但谁在乎……)。我会投票,但出于“某种原因”,我不能(再次)这样做。 ;-)
猜你喜欢
  • 1970-01-01
  • 2015-12-27
  • 1970-01-01
  • 2017-04-03
  • 2022-12-28
  • 2013-03-14
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
相关资源
最近更新 更多