Search code examples
latexr-markdownkableextra

Wrap add_header_above in Rmd pdf output


Question

How to wrap header above (inserted by add_header_above())?

There is a simple way to do it to one layered header but doesn't work when there is a second (or third) of header.

Reproducible example

library(kableExtra)
names(iris) <- c("L", "W", "L", "W", " ")
iris[1:2, ] %>% 
  kable("latex") %>% 
  add_header_above(
    c(
      "Sepal is great" = 2, 
      "Petal is better, (in fac my favorite)" = 2, 
      "nc" = 1)
    ) %>%
  column_spec(2:ncol(iris), width = "0.3in")

Current output looks

enter image description here

Expected output from R code (roughly)

enter image description here


Solution

  • As I said in Best Practice for newline in LaTeX table, if you need newlines inside all kableExtra functions, just use \n. Otherwise, you can try out the linebreak function.

    library(kableExtra)
    names(iris) <- c("L", "W", "L", "W", " ")
    iris[1:2, ] %>% 
      kable("latex") %>% 
      add_header_above(
        c(
          "Sepal\nis great" = 2, 
          "Petal is better,\n(in fac my favorite)" = 2, 
          "nc" = 1)
        ) %>%
      column_spec(2:ncol(iris), width = "0.3in")