8

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

I keep getting this error:

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

Any ideas what does cellcolor needs to work?

user1471980
  • 10,127
  • 48
  • 136
  • 235
  • is this the same question? https://stackoverflow.com/questions/44373073/unable-to-change-the-colors-of-the-xtable-cells-in-rmarkdown-output-to-pdf – M-- Jul 25 '17 at 19:53
  • If I use `xcolor` instead of `color` I'm able to compile the document without error via `rmarkdown::render`. – Peter Jul 25 '17 at 20:42

1 Answers1

4

Update

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

Alternative Approach

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.


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

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.

And this is what you get:

enter image description here

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • I still see this error:! Undefined control sequence. l.91 A & \cellcolor – user1471980 Jul 26 '17 at 13:45
  • Try `devtools::install_github('zeehio/condformat')` – Martin Schmelzer Jul 26 '17 at 14:13
  • I did install the package using install.packages("condformat") – user1471980 Jul 26 '17 at 14:21
  • All I can add is that its working with `RStudio 1.0.143`, `R 3.4.1 `, `condformat 0.6.0.9000` and `knitr 1.16` – Martin Schmelzer Aug 01 '17 at 12:39
  • @user1471980 ; given your difficulty in rendering this, and similar issues on your previous questions, [one](https://stackoverflow.com/questions/44335165/how-do-you-change-colors-of-certain-cells-in-xtable-markdown#comment75841332_44335165), [two](https://stackoverflow.com/questions/44373073/unable-to-change-the-colors-of-the-xtable-cells-in-rmarkdown-output-to-pdf) , this may be something local to your script / tex install, rather than R, and so may benefit from asking at the tex site. (if you do, I would link to each of your questions so all comments can be seen) – user20650 Aug 01 '17 at 13:16
  • Looks like a nice solution and works interactively, but cannot knit this to PDF either. If I hit "knit" in RStudio, it fails with "Error in dimnames(x) <- dn : length of 'dimnames' [2] not equal to array extent Calls: ... -> structure -> condformat2latex -> colnames<-". OTOH, `knit()` successfully produces a MD file. But `knit2pdf` fails with "! Emergency stop *** (job aborted, no legal \end found)". Weird … – CL. Aug 03 '17 at 14:52
  • @CL Try the developer version of condformat if you haven't done it already. – Martin Schmelzer Aug 03 '17 at 14:54
  • 1
    @MartinSchmelzer Indeed, that solves the problem. (At least for the "knit" button in RStudio and `rmarkdown::render`. Not for `knit2pdf` though, but who cares …). I'd upvote but for "some reason" I cannot do that (again). ;-) – CL. Aug 03 '17 at 15:05