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

隐身守侯 提交于 2021-02-20 16:15:12

问题


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.


回答1:


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:




回答2:


Save as HTML within your R script

The readr package has a write_file function that will write data "as it is", so HTML in the case of what you are creating with knitr::kable.

dt <- mtcars[1:5, 1:6]
kable_out <- knitr::kable(dt, "html") %>% kableExtra::kable_styling(bootstrap_options = c("striped", "hover"))
readr::write_file(kable_out, "kable_out.html")

Alternatively: Save as temp.Rmd in R Studio

If you save the following as an R Markdown file (e.g., temp.Rmd) in R Studio, you can create the HTML by clicking Knit at the top-left center of RStudio.

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
```

## Table 1

```{r table1, echo = FALSE}
dt <- mtcars[1:5, 1:6]
knitr::kable(dt, "html") %>% kableExtra::kable_styling(bootstrap_options = c("striped", "hover"))
```

Click Knit in R Studio



来源:https://stackoverflow.com/questions/50257488/save-knitrkable-output-to-html-file-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!