简体   繁体   English

将knitr :: kable()输出保存到html文件R.

[英]Save knitr::kable() output to html file R

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. 我有一个knitr_kable输出,我想从R保存为HTML文档。我需要这个从我的R脚本自动运行,没有人为参与。 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. 这有html输出但类是knitr_kable所以我不能把它写到表或html文件,因为它不能被强制转换为数据帧。

class(kable(dt, "html"))
[1] "knitr_kable"

Does anyone have a method for saving one of these kables as an html file? 有没有人有一种方法可以将这些kables中的一个保存为html文件?


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" UseMethod(“write_html”)中的错误:没有适用于“write_html”的方法应用于类“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. 我的猜测是必须首先将knitr_kable对象强制转换为html对象,然后保存为html文件。 But I'm not sure how to do that. 但我不知道该怎么做。

The cat function will do what you need. cat功能将满足您的需求。

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: 结果表如下所示:

在此输入图像描述

Save as HTML within your R script 在R脚本中另存为HTML

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 . readr包有一个write_file函数,它将“按原样”写入数据,因此在使用knitr::kable创建的内容中使用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 或者:在R Studio中另存为temp.Rmd

If you save the following as an R Markdown file (eg, temp.Rmd) in R Studio, you can create the HTML by clicking Knit at the top-left center of RStudio. 如果在R Studio中将以下内容保存为R Markdown文件(例如,temp.Rmd),则可以通过单击RStudio左上角的编织来创建HTML。

---
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 单击R Studio中的Knit

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM