简体   繁体   English

使用knitr / rmarkdown将R脚本集合编译为HTML

[英]Compile a collection of R scripts to HTML with knitr/rmarkdown

I have a collection of R scripts in a directory and want to compile them all to HTML, as I might do using R Studio Compile Notebook manually, but with some control over the CSS styling. 我在目录中有一组R脚本,想要将它们全部编译为HTML,就像我可以手动使用R Studio Compile Notebook一样,但是可以控制CSS样式。

Each file has a minimal YAML header and a bit of markup, as shown below, and I don't want to introduce additional complexity in the scripts with chunk options except where absolutely necessary. 每个文件都有一个最小的YAML标头和一些标记,如下所示,我不想在带有块选项的脚本中引入额外的复杂性,除非绝对必要。

#' ---
#' title: "Tests for association in two-way tables"
#' author: "Michael Friendly"
#' ---

#' ## Load and examine data
library(vcdExtra)
data(SexualFun)
SexualFun                # show the table
...

I'm confused about which tools to use to compile a single file in this way--- spin | 我对于使用哪种工具以这种方式编译单个文件感到困惑spin | knit2html , markdownToHTML , etc. Once I get this right, I can use something like apply() to do it for my list of files, files <- list.files(pattern="*.R$") . knit2htmlmarkdownToHTML等,一旦我得到这个权利,我可以使用类似于apply()这样做对我的文件,列表files <- list.files(pattern="*.R$")

Here's what I've tried to compile one file, with some additional control: 这是我尝试通过一个附加控件来编译一个文件的方法:

library(knitr)
options(markdown.HTML.options = markdownHTMLOptions(stylesheet = "markdown.css"))
knit_theme$set("seashell")
opts_chunk$set(fig.align="center")
spinone <- function(file, outdir="output/") {
    fn <- knitr:::sans_ext(file)
    #+ suppressmessages, include=FALSE
    knitr::opts_chunk$set(warning = FALSE, message = FALSE)
    spin(file)
    Rmd <- knitr:::sub_ext(file, "Rmd")
    out <- paste0(outdir, knitr:::sub_ext(file, "html"))
    knit2html(Rmd, output=out)
}

But it doesn't work correctly. 但是它不能正常工作。 I get: 我得到:

> spinone("sexfun-chisq.R")
processing file: sexfun-chisq.Rmd
  ...
  |.................................................................| 100%
  ordinary text without R code

output file: sexfun-chisq.md

Error in readLines(if (is.character(input2)) { : 
  cannot open the connection
In addition: Warning message:
In readLines(if (is.character(input2)) { :
  cannot open file 'sexfun-chisq.Rmd': No such file or directory

Actually, sexfun-chisq.html is produced, but it doesn't have the YAML header and doesn't use my style options. 实际上,产生了sexfun-chisq.html ,但是它没有YAML标头,也不使用我的样式选项。

使用spin(file, knit = FALSE)以便不会删除Rmd文件(请参阅?spinprecious参数)。

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

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