Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save knitr::kable() output to html file R

Tags:

r

knitr

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.

like image 418
conv3d Avatar asked May 09 '18 15:05

conv3d


People also ask

How do I save a Rmarkdown file as HTML?

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.

What is knitr :: Kable?

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.

What is Kable package in R?

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.

How do I change the size of a Kable table?

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%;'") .


1 Answers

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:

enter image description here

like image 192
Peter Avatar answered Oct 07 '22 14:10

Peter