Search code examples
rpdflatexkableextra

R kable formatted with kableExtra::cell_spec() gives verbatim latex-commands instead of expected format


Problem

  • R Markdown with RStudio
  • Knitting to PDF
  • kable formatted with kableExtra::cell_spec() gives verbatim latex-commands instead of expected format

Questions

  • Is it reproducible in other environments?
  • Any ideas for solution?

RMD commands

---
title: "MWE cell_spec latex"
author: "Thomas"
date: "2022-12-16"
output: 
 pdf_document:
   keep_tex: yes

---

```{r setup, include=TRUE }


library("tidyverse")
library("kableExtra")

data <- data.frame(item=c("I'm red", "What color am I?"))

kable(data)

data %>%
  mutate(item = cell_spec(item, "latex",color = "red"))%>%
  kable()


```

Tex-File in tabular-environment

The tex-file shows, that pandoc outputs \textbackslash{} for the cell specification instead of \

\begin{verbatim}

\begin{tabular}{l} \hline item\ \hline \textbackslash{}textcolor{red}{I'm red}\ \hline \textbackslash{}textcolor{red}{What color am I?}\ \hline \end{tabular}

\end{verbatim}


Solution

  • You are very nearly there. Try:

    ---
    title: "MWE cell_spec latex"
    author: "Thomas"
    date: "2022-12-16"
    output: 
     pdf_document:
       keep_tex: yes
    
    ---
    
        ```{r setup, results=`asis` }
        
        
        library(dplyr)
        library(kableExtra)
        
        data <- data.frame(item=c("I'm red", "What color am I?"))
        
        data  |> 
          mutate(item = cell_spec(item, "latex", color = "red")) |> 
          kable(escape = FALSE)
        
        ```