Search code examples
rlatexknitrkableextra

R kableExtra latex: Add linebreaks to rotated header row


I'm trying to produce table to a Latex-pdf document. I'm using kableExtra and knitr in R.

I have a table that has long column names. When I rotate the header row by 90 degrees linebreaks won't work. Does anyone have an idea how I could achieve both rotated row and linebreaks?

My example is the same as in Hao's Best Practice for newline in Latex table, but I added piped row_spec to the end of the code.

\documentclass[10pt,a4paper]{article}
\usepackage[table]{xcolor}

\begin{document}
\begin{table}
<<global_options, echo=FALSE>>=
library(kableExtra)
library("dplyr")
dt_lb <- data.frame(
  Item = c("Hello\nWorld", "This\nis a cat"),
  Value = c(10, 100)
)
dt_lb %>%
  mutate_all(linebreak) %>%
  kable("latex", booktabs = T, escape = F,
        col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"))) %>%
  row_spec(0, angle = 90, align='l', monospace=T)

@

\end{table}
\end{document}

What I get is this, but the [l] tags hint that there's something else wrong with the tags as well:

enter image description here

On StackExchange TEX I found a question about rotation and linebreaks, this is what I'm trying achieve: https://tex.stackexchange.com/questions/14730/big-table-with-rotated-column-labels-using-booktabs


Solution

  • Latex package makecell was missing.

    Hao pointed out that Page 3 of this manual lists some of the necessary Latex packages: haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf