Dynamic kableExtra latex table widths, wrap long column

Viewed 187

I would like to not rely on column_spec to hardcode column widths, since the business scenario here is we will be creating tables with long column names and changing number of columns.

How do I let Kable / RMarkdown:

  • decide the column widths so it does not overflow the page width
  • populate the full page width and wrap long columns
  • respect page margins?

Happy to insert latex lines! i.e. some setting with \textwidth? But I am not fluent enough in latex to integrate the codes in :( Please do not tweak latex engine, or type of table (i.e. tabu or longtable) because I only got the stylings to work with the current booktabs = TRUE setting and the latex tabular table type. enter image description here current

---
title: "Untitled"
output: 
  pdf_document: 
    latex_engine: xelatex
header-includes: \usepackage{fontenc} \usepackage[T1]{fontenc} \usepackage{titling}
---

```{r setup, warning=FALSE, echo=FALSE}
library(kableExtra)

tbl <- dplyr::tibble('name' = c("a pretty long name to start with",
                                "another pretty long name"),
                     'here comes a long column name' = c(1021, 54801),
                     'another column' = c(342, 52432),
                     'yet another' = c("SHDFJI50", "FEUAS453"),
                     'another one' = c("text", "more and more text"))

kbl(tbl, booktabs = TRUE, linesep = "\\hline", align = c("c")) %>%
  row_spec(0, background = "black", color = "white") %>%
  add_header_above(c("header" = 3, "more headerssss" = 2), 
                   color = "white", background = "black", escape = TRUE) %>%
  column_spec(c(1:2), width = "8em", bold = FALSE) %>%  # to be remove
  column_spec(c(3,4), width = "7em", bold = FALSE) %>%   # to be removed
  sub("\\\\bottomrule", "", .) %>%
  sub("\\\\toprule", "", .)

```
0 Answers
Related