Forced line break in kable/kableExtra table


#1

Hi

How can I insert a line break in the cells of the last column in the following table?
That is I would "1[val1, val2]" (and similar entries) to be shown as
1
[val1, val2]

Thanks in advance for you help

require(knitr)
require(kableExtra)

dat <- data.frame(
  parms = letters[1:5],
  A = 1:5,
  B = 11:15,
  C = LETTERS[26:21],
  D = c('1[va1, val2]', '2[va1, val2]', '3[va1, val2]', '4[va1, val2]', '5[va1, val2]')
)

kable(dat, format = 'latex', booktabs = T) %>%
  kable_styling() %>%
  add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2))

#2

This document outlines two solutions: you can either pipe your table into column_spec to make the column a fixed width (and line breaks should be taken care of), or you can wrap your column values in linebreak, which allows you to drop \n in the values where you want your line breaks (the linebreak function will substitute \n for the required formatting).

Hope those solutions help!


#3

Thanks for the link.
The linebreak function looks like what I need. Unfortunately, I will have to submit a feature request because it does not seem to work with cells containing ['. Not sure if additional special characters would be an issue...


#4

That's frustrating. What sort of problem are you having when you add [ to the cell contents?


#5

Using the following code, the compilation is successful but the cells in the 4th column report \makecell[1]{#\[val1,val2]}, where # is 1 to 5.

The line breaks is correctly inserted when the [ characters are substituted by ('s or various other characters.

dat <- data.frame(
  parms = letters[1:5],
  A = 1:5,
  B = 11:15,
  C = LETTERS[26:30],
  D = c('1\n[va1, val2]', '2\n[va1, val2]', '3\n[va1, val2]', '4\n[va1, val2]', '5\n[va1, val2]')
)

 dat %>%
  mutate_all(linebreak) %>%
  kable(format = 'latex', booktabs = TRUE) %>%
  kable_styling() %>%
  add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2))

If I also used the recommend escape = FALSE option in the kable call, I get an compilation error:

dat %>%
  mutate_all(linebreak) %>%
  kable(format = 'latex', booktabs = TRUE, escape = FALSE) %>%
  kable_styling() %>%
  add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2))

...

! Missing number, treated as zero.
<to be read again> 
                   v
l.111 ...1 & 11 & 1 & \makecell[l]{1\\[va1, val2]}

pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43
Execution halted