I have a knitr_kable output that I want to save as an HTML document from R. I need this to run automatically from my R script with no human involvement. For example:
dt <- mtcars[1:5, 1:6]
kable(dt, "html") %>% kable_styling(bootstrap_options = c("striped", "hover"))
This has html output but the class is knitr_kable
so I can't write it to a table or html file because it cannot be coerced to a dataframe.
class(kable(dt, "html"))
[1] "knitr_kable"
Does anyone have a method for saving one of these kables as an html file?
I've tried:
library(xml2)
options(knitr.table.format = "html")
write_html(kable(dt, "html"), "df.html")))
This has error:
Error in UseMethod("write_html") : no applicable method for 'write_html' applied to an object of class "knitr_kable"
My guess would be that the knitr_kable object must first be coerced to an html object and then saved as html file. But I'm not sure how to do that.
To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want. When you click the button, rmarkdown will duplicate your text in the new file format.
10.1 The function knitr::kable() The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.
Description. A very simple table generator, and it is simple by design. It is not intended to replace any other R packages for making tables. The kable() function returns a single table for a single data object, and returns a table that contains multiple tables if the input object is a list of data objects.
By defining the table format and adding some CSS styling you can change the size of the like so: knitr::kable(x, format = "html", table. attr = "style='width:30%;'") .
The cat
function will do what you need.
library(knitr)
library(kableExtra)
library(magrittr)
dt <- mtcars[1:5, 1:6]
kable(dt, "html") %>%
kable_styling(bootstrap_options = c("striped", "hover")) %>%
cat(., file = "df.html")
The resulting table looks like this:
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