Search code examples
rr-markdownkableextra

How to change textcolor for kableExtra()-footnote in RMarkdown PDF?


I'm creating a Rmarkdown PDF-report with tables in kableExtra(). Is there a way to change the textcolor of the footnotes according to the conditional formatting set in cell_spec()?

I tried to use paste0(), see the minimal reprex (from kableExtra) below. I cannot change the PDF output and the request is for a client.

Im running R version 3.5.1 (2018-07-02), Platform: x86_64-apple-darwin15.6.0 (64-bit), Running under: macOS 10.14.2 and kableExtra_0.9.0.

---
title: "Minimal Reprex"
output: pdf_document
---

```{r setup, include=FALSE}

knitr::opts_chunk$set(echo = TRUE)

# packages
library(dplyr)
library(kableExtra)
```


```{r reprex}
mtcars[1:10, 1:2] %>%
   mutate(
    car = row.names(.),
    # You don't need format = "latex" if you have ever defined 
      options(knitr.table.format)
    mpg = cell_spec(mpg, "latex", color = ifelse(mpg > 20, "red", 
     "black")),
    cyl = cell_spec(cyl, "latex", color = "white", align = "c", 
     angle = 45,
    background = factor(cyl, c(4, 6, 8),
    c("#666666", "#999999", "#BBBBBB")))) %>%
    select(car, mpg, cyl) %>%
    kable("latex", escape = F, booktabs = T, linesep = "") %>% 
    footnote(paste0("MPG > 20 is displayed in", "\textcolor{red} 
    {red}"))

  ```

I expect the word "red" to be coloured in red, where as I get "\textcolor{red}{red}" - it just pastes this text. I know there's a problem with pasting the latex-code, but I cannot figure it out.


Solution

  • Use four backslashes and the option escape = F:

    footnote("MPG > 20 is displayed in \\\\textcolor{red}{red}", escape = F)
    

    Without escape = F, characters with a special meaning to LaTeX (like \ & % { }) will be escaped with the result, that you have the character itself in your output document. Here we manually escape the backslashes (in the resulting tex document will be only one).