R knitr Add linebreak in table header kable()

There is a way to limit column width which you could use to help achieve this in kable. use column_spec() where you can specify which columns, and the width in different units like cm,in,em.


As far as I know, the pipe table syntax does not support line breaks in the cells, so if using pandoc to convert markdown to HTML (this is what RStudio uses), then you'd better choose some more feature-rich table syntax, e.g. multiline or grid. Not sure how to do that with kable, but pander supports those:

> library(pander)
> colnames(s) <- c("Try Newline\nn","Try HTML break<br>%","Past 6 months\nn","\n%")
> pander(s, keep.line.breaks = TRUE)

-------------------------------------------------------
 Try Newline   Try HTML break<br>%   Past 6 months   % 
      n                                    n           
------------- --------------------- --------------- ---
      1                 2                  3         4 

      1                 2                  3         4 

      1                 2                  3         4 
-------------------------------------------------------

But this is not enough, as line breaks are automatically removed by pandoc, so you have to put hard line-breaks ("a backslash followed by a newline") there based on the related docs. E.g. the following code converts to HTML as expected:

> colnames(s) <- c("Try Newline\\\nn","Try HTML break\\\n%","Past 6 months\\\nn","\\\n%")
> pander(s, keep.line.breaks = TRUE)

-----------------------------------------------------
 Try Newline\   Try HTML break\   Past 6 months\   \ 
      n                %                n          % 
-------------- ----------------- ---------------- ---
      1                2                3          4 

      1                2                3          4 

      1                2                3          4 
-----------------------------------------------------

So it appears that kable converts the <> to HTML equivalents, i.e. "&lt;" and "&gt;", so I have a quick fix that will work as long as you don't actually require the <> anywhere else. This has allowed me to get a line break in the column headings in my table.

Essentially once your table is complete just substitute the "&lt;" and "&gt;" in the HTML for < and > and then save it as HTML file. Like so:

tbl_output <- gsub("&lt;", "<", tbl_output)
tbl_output <- gsub("&gt;", ">", tbl_output)

write(tbl_output, "TableOutput.html")

where tbl_output is the output from kable.

Alternatively, and in particular if you need to use <> elsewhere in your table, you could create your own string for a newline and then gsub it for <br> at the end.

Tags:

Html

R

Knitr