Search code examples
rr-markdownknitrtabularkableextra

Set col names and headers (above) to weird characters for tables with knitr, kableExtra and Latex in R markdown


I'm trying to create a table in Rmarkdown (for pdf) based on the diamonds data set and I want to change some column names and headers above the column names, I would like to know how I can set some headers in italic or bold and some headers should be a symbol (like the one for partial eta squared) or a complete formula. I've included my R code (and I have installed Latex) with the table as a picture (not adjusted yet).

```{r setup, include=FALSE}

setwd("~/Desktop/Tables") 
knitr::opts_chunk$set(echo = FALSE)
# global options
options(knitr.table.format = "latex") 
# show space instead of NA in tables
options(knitr.kable.NA = '')
library(tidyverse)
library(knitr)
library(kableExtra)
df = diamonds

```

```{r message=FALSE, warning=FALSE}

df_table = df %>% 
  summarise(avg = round(mean(price), 2),
            sd = round(sd(price), 2),
            n = n(),
            range = round(max(price), 2)) %>% 
  mutate(grouping = "Total") %>% 
  select(grouping, avg, sd, n, range) %>% 
  bind_rows(df %>% 
              group_by(cut) %>% 
              summarise(avg = round(mean(price), 2),
              sd = round(sd(price), 2),
              n = n(),
              range = round(max(price), 2)) %>% 
              mutate(grouping = as.character(cut)) %>% 
              select(grouping, avg, sd, n, range))

kable(df_table,
      booktabs = TRUE,
      linesep = "",
      col.names = c("Grouping", "M in italic", "SD in italic", "N not 
italic", "some weird formula for the range" )) %>%
  kable_styling(latex_options = c("HOLD_position", "scale_down")) %>% 
  add_header_above(c(" " = 1, "the formula for the variance" = 4))

```

enter image description here


Solution

  • Set escape = FALSE in your call to kable and add_header_above and use LaTeX in your column headings. I should admit that it's a mystery to me exactly how many backslashes should be added to get the desired result.

    kable(df_table,
          booktabs = TRUE,
          linesep = "",
          col.names = c("Grouping", "$M$", "$SD$", "N", "$\\eta$"), escape = FALSE) %>%
      kable_styling(latex_options = c("HOLD_position", "scale_down")) %>% 
      add_header_above(c(" " = 1, "$\\\\operatorname{Var}[X]$" = 4), escape = FALSE)
    

    enter image description here