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.
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.")
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With