user101089
user101089

Reputation: 3992

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.

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.

#' ---
#' 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|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$").

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.

Upvotes: 1

Views: 1217

Answers (1)

Yihui Xie
Yihui Xie

Reputation: 30174

Use spin(file, knit = FALSE) so that the Rmd file will not be deleted (see the precious argument in ?spin).

Upvotes: 1

Related Questions