rend.R 1.91 KB
Newer Older
Holger Brandl's avatar
Holger Brandl committed
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env Rscript

# 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

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

# retrieve and parse the command-line arguments
doc <- '
Holger Brandl's avatar
Holger Brandl committed
14
15
Use rmarkdown to render R and Rmd into html documents
Usage: rend.R [options] <r_script> [<quoted_script_args>]
Holger Brandl's avatar
Holger Brandl committed
16
17
18
19
20
21
22
23
24
25

Options:
--toc     Add a table of contents
-c        Cache results
-e        Show Code
-w        Show warnings
-m        Show Messages
--keep    Keep generated Rmd and md files
'

Holger Brandl's avatar
Holger Brandl committed
26
opts <- docopt(doc)
Holger Brandl's avatar
Holger Brandl committed
27

Holger Brandl's avatar
Holger Brandl committed
28
29
r_script <- opts$r_script
keep_markdown_files <- as.logical(opts$keep)
Holger Brandl's avatar
Holger Brandl committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

if(keep_markdown_files){
    print("keeping markdown files")
}

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

Holger Brandl's avatar
Holger Brandl committed
47
commandArgs <- function(trailingOnly = FALSE){ return(as.character(opts$quoted_script_args)) }
Holger Brandl's avatar
Holger Brandl committed
48
49
50
51
52
53
54

#system(paste("cat ", r_script," | grep -Ev '^#+$' | grep -Fv '#!/usr/bin/env Rscript' >", basename(r_script)))
#r_script <- basename(r_script)


## custom title http://stackoverflow.com/questions/14124022/setting-html-meta-elements-with-knitr
opts_chunk$set(
Holger Brandl's avatar
Holger Brandl committed
55
56
57
58
    cache = opts$c,
    message= opts$m,
    warning= opts$w,
    echo= opts$e,
Holger Brandl's avatar
Holger Brandl committed
59
60
61
62
63
    fig.width=15,
    width=200
)

rmarkdown::render(input=r_script,
Holger Brandl's avatar
Holger Brandl committed
64
    output_format=rmarkdown::html_document(toc = opts$toc, keep_md=keep_markdown_files),
Holger Brandl's avatar
Holger Brandl committed
65
66
67
68
69
70
71
72
73
74
    output_dir=getwd(),
    output_options=list(toc="yes")
)

## also remove the .md and the .Rmd files
if(is.logical(keep_markdown_files) & !keep_markdown_files){
#    file.remove(basename(rmdScript))
#    file.remove(basename(str_replace(r_script, "[.]R$", ".md")))
}