Search code examples
rkablekableextra

R kableExtra with header expression


given the following reproducible example

---
title: "test kable"
output: pdf_document
---


```{r}

mydf <- data.frame(a=1:3, b = letters[1:3])

mydf |> 
knitr::kable(col.names = c("A", "B")) |> 
#kableExtra::add_header_above(c("title" = 2)) |> # this is working fine
kableExtra::add_header_above(c("$\\mu$" = 2)) # but this don't
# here I want to insert a title spanning multiple columns containing an expression
# e.g. something like: expression(paste("PM10 [ ", mu*g~m^-3, " ]"))
```

my goal is to insert in a kable header an expression containing some greek symbols (see above);

please also consider I need to have a latex output;

by the way I've also defined inside the Rmarkdown file a new command by:

\newcommand{\ugmc}{\si{\micro\gram\per\cubic\meter}}

after having inserted \usepackage{siunitx} inside the preamble of the tex template file (but, this is another story, just mentioned here for framing the full context)

any help pointing me in the right direction?

thanks


Solution

  • You could use escape = FALSE with \\\\ to insert greek letters like this:

    ---
    title: "test kable"
    output: pdf_document
    
    ---
    
    ```{r}
    mydf <- data.frame(a=1:3, b = letters[1:3])
    
    mydf |> 
    knitr::kable(col.names = c("A", "B"), 'latex') |> 
    kableExtra::add_header_above(c("$\\\\beta$" = 2), escape = FALSE) 
    ```
    
    ```{r}
    mydf <- data.frame(a=1:3, b = letters[1:3])
    
    mydf |> 
    knitr::kable(col.names = c("A", "B"), 'latex') |> 
    kableExtra::add_header_above(c("$PM10[\\\\mu*g\\\\sim m^{-3}]$" = 2), escape = FALSE) 
    ```
    

    Output:

    enter image description here