Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Column-Names to Wrap in R/Kable() HTML Table

I'm trying to produce an HTML table output from an R data frame and am unable to get some long column names to wrap for a multi-line header row. Here is a minimal reproducible example of my current code and output:

library(datasets)
library(knitr)
library(kableExtra)

data(iris)

Output top 5 rows of iris table as html formatted table:

sink('my_file_path.html')
names_spaced <- c('Sepal Length', 'Sepal Width', 'Petal Length', 
                  'Petal Width Long Col Name', 'Species')

kable(head(iris), 
      format='html', 
      digits=1, 
      row.names=FALSE, 
      align='lccccc', 
      col.names = names_spaced)

sink()

When I open the saved file in the browser, my header row is just one line, but I need the words to wrap to one or two lines (hence 'Petal Width Long Col Name').

kable_styling function has a param bootstrap_options but that doesn't seem to have what I need. I also tried inserting \n within the column-names but to no avail.

I am not averse to using the xtable package instead of kable/knitr if that's part of the solution.

like image 665
Max Power Avatar asked Jun 29 '17 04:06

Max Power


People also ask

How do you put a title on a Kable table?

You can add a caption to the table via the caption argument, e.g. (see Table 10.1 for the output), knitr::kable(iris2, caption = "An example table caption.")

What package is Kable in R?

Function 'kable()' is a light weight table generator coming from 'knitr'. This package simplifies the way to manipulate the HTML or 'LaTeX' codes generated by 'kable()' and allows users to construct complex tables and customize styles using a readable syntax.


1 Answers

It is possible to create linebreaks with HTML syntax. In order for that to work, you will have to set the escape argument of kable to FALSE.

library(knitr)
data(iris)

sink('my_file_path.html')
names_spaced <- c(
  'Sepal Length', 'Sepal Width', 'Petal Length', 
  'Petal Width<br/> Long Col Name',                  ## add <br/>
  'Species')

kable(head(iris), 
      format='html', 
      digits=1, 
      row.names=FALSE, 
      align='lccccc', 
      col.names = names_spaced,
      escape = FALSE)                                ## disable html escape to 
                                                     ## make <br/> work

sink()
like image 92
Gregor de Cillia Avatar answered Sep 19 '22 08:09

Gregor de Cillia