Search code examples
rknitrkable

Inserting new lines into kable headers


Problem description:

I'm writing a document in rMarkdown and I need to format a table before producing a PDF. The issue is that I'm having trouble inserting a new line in my kable headers that have been added using the add_headers_above command.

Currently the text "Month (persons)" - which is the first header added with that command - appears as one line. I'd like to break that so that a new line is inserted between "Month" and "(persons)".

The motivation is simply to save horizontal page space so that I can fit two tables size by size on one A4 sheet.

My attempt at the fix

I've tried to include \n in the add_headers_above command:

[...] %>% add_header_above(c(" ", 'Month \n (persons)' = 1, "TTY \n (persons)" = 1, "TTY \n (% chg.)" = 1)) But that hasn't worked.

Reproducible example:

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)
library(tibble)
```
```{r}
df <- tribble(~Location, ~Jan_Qrt, ~Jan_year, ~growth,
"New South Wales",  16000,  403300,       3.30,
"Victoria",        -21200,    134100,       3.50,
"Queensland",        2100,  100200,       3.20,
"South Australia",  19700,  117900,       5.00,
"Western Australia",   5300,   13200,     1.60,
"Tasmania",         -8900,   24300,     1.90,
"Northern Territory",    -400,    5700,    2.40,
"Australian Cap",     300,   -4300,    -3.10,
"Australia",         800,   10600,     4.80)

kable(df, format = 'latex', booktabs = T, align = 'r') %>%
  kable_styling(full_width = F, font_size = 8) %>%
  row_spec(row = 9, bold = TRUE) %>%
  add_header_above(c(" ", 'Month (persons)' = 1, "TTY (persons)" = 1, "TTY (% chg.)" = 1))

  ```

Solution

  • For now, you will have to write some raw latex code by yourself.

    As the answer in https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell suggested, you can try to use the makecell package. To do that, you can load the latex package using kableExtra::usepackage_latex() and then hack it through setting escape = F in add_header_above.

    usepackage_latex("makecell")
    kable(df, format = 'latex', booktabs = T, align = 'r') %>%
      kable_styling(full_width = F, font_size = 8) %>%
      row_spec(row = 9, bold = TRUE) %>%
      add_header_above(c(" ",
                         '\\\\thead{Month\\\\\\\\(persons)}' = 1,
                         "\\\\thead{TTY\\\\\\\\(persons)}" = 1,
                         "\\\\thead{TTY\\\\\\\\(\\\\% chg.)}" = 1),
                       escape = F)
    

    Update

    Never mind the latex mess above, I made it work in the dev version of kableExtra. Now you just do

    library(kableExtra)
    
    mtcars[1:5, 1:5] %>%
      kable("latex", booktabs = T) %>%
      add_header_above(c(" ", "aa\na" = 2, "bbb" = 3))