Wietze314
Wietze314

Reputation: 6020

R knitr Add linebreak in table header kable()

I am using knitr to generate some reports. I use kable to generate an HTML table in the document. In the headers I want to use linebreaks (or other html tags) to enhance the table

<!--begin.rcode results='asis'
s <- rbind(c(1,2,3,4),c(1,2,3,4),c(1,2,3,4))
kable(s, col.names=c("Try Newline\nn","Try HTML break<br>%","Past 6 months\nn","\n%"))
end.rcode-->

As you can see I am trying different options without much success. In my result linebreaks (\n) are just translated in a linebreak in the HTML source.
tags are translated to HTML special characters.

Any suggestions?

Upvotes: 15

Views: 15211

Answers (5)

stm
stm

Reputation: 111

Another option is to use column_spec(1:4, width="3cm") to limit the width, which adds linebreaks automatically. It affects the entire column unfortunately, but works on format=latex and escape=T

Upvotes: 0

robertspierre
robertspierre

Reputation: 4441

With latex output, you can use the makecell LaTeX package, together with escape=FALSE.

escape=FALSE will prevent \\ to be substituted with \textbackslash{} in the intermediate LaTeX output.

Here is a MWE:

---
header-includes:
- \usepackage{makecell}
output: beamer_presentation
---

# Ch 1

## Ch 1.1

```{r, echo=FALSE}
library(kableExtra)
s <- rbind(c(1,2,3,4),c(1,2,3,4),c(1,2,3,4))
cnames <- c("\\makecell[ct]{Distance\\\\km}",
                     "\\makecell[ct]{Power\\\\W}",
                     "\\makecell[ct]{Energy\\\\J}",
                     "\\makecell[ct]{Pressure\\\\Pa}")
kable(s, col.names=cnames, escape=FALSE)

enter image description here

Upvotes: 2

SMorris
SMorris

Reputation: 21

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.

Upvotes: 2

Sahir Moosvi
Sahir Moosvi

Reputation: 598

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.

Upvotes: 4

daroczig
daroczig

Reputation: 28672

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 
-----------------------------------------------------

Upvotes: 14

Related Questions