R knitr Add row to table header kable ()

I use knitr to create some reports. I use kable to create an HTML table in a document. In the headers I want to use linebreaks (or other html tags) to improve 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 try different options without much success. In my result, linebreaks (\ n) have just been translated to linebreak in the HTML source. Tag tags translate to special HTML characters.

Any suggestions?

+5
source share
3 answers

As far as I know, pipe table syntax does not support line breaks in cells, therefore, if you use pandoc to convert markdowns to HTML (this is what RStudio uses), then you better choose another table syntax with a lot of functions, for example multiline or grid . You do not know how to do this with kable , but pander supports the following:

 > 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 % nn ------------- --------------------- --------------- --- 1 2 3 4 1 2 3 4 1 2 3 4 ------------------------------------------------------- 

But this is not enough, since line breaks are automatically deleted using pandoc , so you have to set hard line breaks ("backslash followed by a new line"), based on related documents . For instance. The following code will convert 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 ----------------------------------------------------- 
+9
source

There is a way to limit the column width that you can use to achieve this in Kable. use column_spec() where you can specify which columns as well as the width in different units, for example, see, in, em.

0
source

So it seems that kable will convert <> to HTML equivalents, that is, "&lt;" and "&gt;" So, I have a quick fix that will work until you really require <> somewhere else. This allowed me to get a line break in the column headers in my table.

Essentially, after populating the table, simply replace "&lt;" and "&gt;" in HTML for <and>, and then save it as an HTML file. Like this:

 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 the table, you can create your own row for the new row and then add it for gsub
in the end.

0
source

All Articles