Skip to content
Snippets Groups Projects
spin.R 2.08 KiB
Newer Older
#!/usr/bin/env Rscript

Holger Brandl's avatar
Holger Brandl committed
# similar http://stackoverflow.com/questions/10943695/what-is-the-knitr-equivalent-of-r-cmd-sweave-myfile-rnw

#http://stackoverflow.com/questions/3433603/parsing-command-line-arguments-in-r-scripts
#https://github.com/edwindj/docopt.R
#http://www.slideshare.net/EdwindeJonge1/docopt-user2014

## a thin wrapper around spin to make it more useful with more custom output
#devtools::source_url("https://dl.dropboxusercontent.com/u/113630701/datautils/R/core_commons.R")

# load the docopt library
suppressMessages(library(docopt))

# retrieve and parse the command-line arguments
doc <- '
Use knitr to spin R documents
Usage: spin.R [-cewm] <r_script> [<script_args>...]

Options:
-c        Cache results
-e        Show Code
-w        Show warnings
-m        Show Messages
'
#docopt(doc, "-w test  a b c ")$"-w"

Holger Brandl's avatar
Holger Brandl committed
spin_opts <- docopt(doc)
#print(spin_opts)
Holger Brandl's avatar
Holger Brandl committed
r_script <- spin_opts$r_script

if(!file.exists(r_script)){
     stop(paste("file does not exist\n", doc))
}


require(plyr)
require(knitr)
require(stringr)

options(width=150)

#https://groups.google.com/forum/#!topic/knitr/ojcnq5Nm298

## better table css: http://www.stat.ubc.ca/~jenny/STAT545A/topic10_tablesCSS.html
Holger Brandl's avatar
Holger Brandl committed
commandArgs <- function(trailingOnly = FALSE){ return(as.character(spin_opts$script_args)) }
#print("trimmed args are")
#print(commandArgs())
#print("end args")

spin(r_script, knit=F)

Holger Brandl's avatar
Holger Brandl committed
rmdScript <- str_replace(r_script, "[.]R$", ".Rmd")
Holger Brandl's avatar
Holger Brandl committed
system(paste("mv", rmdScript, "tmp.Rmd"))
system(paste("cat tmp.Rmd | grep -Ev '^#+$' | grep -Fv '#!/usr/bin/env Rscript' >", basename(rmdScript)))
file.remove("tmp.Rmd")

cssHeader='
<style type="text/css">
  body {
      max-width: 90%;
  }
</style>
'

## custom title http://stackoverflow.com/questions/14124022/setting-html-meta-elements-with-knitr
opts_chunk$set(
Holger Brandl's avatar
Holger Brandl committed
    cache = spin_opts$c,
    message= spin_opts$m,
    warning= spin_opts$w,
    echo= spin_opts$e,
    fig.width=15,
    width=200
)

Holger Brandl's avatar
Holger Brandl committed
knit2html(basename(rmdScript), header=cssHeader)

## also remove the .md and the .Rmd files
file.remove(basename(rmdScript))
file.remove(basename(str_replace(r_script, "[.]R$", ".md")))