Search code examples
htmlrknitr

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?


Solution

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