user
user

Reputation: 23

column_spec in R's kable does not change columns possibly due to headers

I want to reduce the width of my columns for my latex-rmarkdown pdf output but it doesn't seem to work.

desired output

desired output


column_spec() is unable to adjust the width of the headers and they are not able to wrap.

kable_styling(latex_options = "scale_down", full_width = F) |> 
  column_spec(2:8, width = "5em") |> 

My Output

My output

Upvotes: 1

Views: 421

Answers (1)

Carlos Luis Rivera
Carlos Luis Rivera

Reputation: 3633

You can add a header for group columns via kableExtra::add_header_above(). When you insert such a header into a table, you can specify the width of that header by using a LaTeX command \parbox{..width..}{..contnets..}. To use any LaTeX command in a table created using knitr::kable() and kableExtra's functions, you have to set escape = FALSE in these functions.

enter image description here

mtcars |>
  head() |>
  knitr::kable(
    "latex",
    booktabs = TRUE
  ) |>
  kable_styling(
    latex_options = "scale_down",
    full_width = FALSE
  ) |>
  column_spec(
    1:2,
    width = "5em"
  ) |>
  add_header_above(
    c(
      " ",
      "\\\\parbox{5em}{this header for group columns is way too long and I want to wrap this but I don't know how}" = 5,
      "Group 2" = 6
    ),
    escape = FALSE
  )

Upvotes: 1

Related Questions