Reputation: 8954
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.
Upvotes: 14
Views: 9226
Reputation: 7635
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()
Upvotes: 14