r - how do you color the cell in rmarkdown pdf output -


i cannot cellcolor work in rmarkdown:

--- header-includes:    -  \usepackage{colortbl}     -  \usepackage{color}   output:     pdf_document ---  ```{r, results="asis"}  library(xtable) # data tab = data.frame(category = c("a","b","c"), groupa = c(.2,.3,.5), groupb= c(.6,.7,.9))  # function cut data, , assign colour 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 columns: overwrites 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 error:

! undefined control sequence. l.155 1 & & \cellcolor 

any ideas cellcolor needs work?

update

the op's example works me when including \usepackage[dvipsnames]{xcolor} instead. approach see below.

alternative approach

here approach using handy condformat package. way don't have include tex packages hand , don't have worry escaping special characters etc.


we create condformat_tbl object , add 2 formatting rules each column.

--- output:     pdf_document ---  ```{r, include = f} library(condformat) cols        <- c('green', 'red', 'blue', 'orange',                   'yellow', 'purple', 'brown', 'white') names(cols) <- cols # important colours arg in rule_fill_discrete                     # since matches result of 'expression' names of '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, value colours argument in rule_fill_discrete vector of key-value pairs. keys possible results of expression.

and get:

enter image description here


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -