| 1 |
#' Automatically create a report based on an R script and a template |
| 2 |
#' |
| 3 |
#' This is a convenience function for small-scale automatic reporting based on |
| 4 |
#' an R script and a template. The default template is an Rnw file (LaTeX); |
| 5 |
#' \code{stitch_rhtml()} and \code{stitch_rmd()} are wrappers on top of |
| 6 |
#' \code{stitch()} using the R HTML and R Markdown templates respectively. |
| 7 |
#' |
| 8 |
#' The first two lines of the R script can contain the title and author of the |
| 9 |
#' report in comments of the form \samp{## title:} and \samp{## author:}. The |
| 10 |
#' template must have a token \samp{\%sCHUNK_LABEL_HERE}, which will be used to |
| 11 |
#' input all the R code from the script. See the examples below. |
| 12 |
#' |
| 13 |
#' The R script may contain chunk headers of the form \samp{## ---- label, |
| 14 |
#' opt1=val1, opt2=val2}, which will be copied to the template; if no chunk |
| 15 |
#' headers are found, the whole R script will be inserted into the template as |
| 16 |
#' one code chunk. |
| 17 |
#' @param script Path to the R script. |
| 18 |
#' @param template Path of the template to use. By default, the Rnw template in |
| 19 |
#' this package; there is also an HTML template in \pkg{knitr}. |
| 20 |
#' @param output Output filename, passed to \code{\link{knit}}). By default, |
| 21 |
#' the base filename of the script is used. |
| 22 |
#' @inheritParams knit |
| 23 |
#' @return path of the output document |
| 24 |
#' @export |
| 25 |
#' @seealso \code{\link{spin}} (turn a specially formatted R script to a report) |
| 26 |
#' @examples s = system.file('misc', 'stitch-test.R', package = 'knitr') |
| 27 |
#' if (interactive()) stitch(s) # compile to PDF |
| 28 |
#' |
| 29 |
#' # HTML report |
| 30 |
#' stitch(s, system.file('misc', 'knitr-template.Rhtml', package = 'knitr')) |
| 31 |
#' |
| 32 |
#' # or convert markdown to HTML |
| 33 |
#' stitch(s, system.file('misc', 'knitr-template.Rmd', package = 'knitr')) |
| 34 |
#' |
| 35 |
#' unlink(c('stitch-test.html', 'stitch-test.md', 'figure'), recursive = TRUE) |
| 36 |
stitch = function(script, |
| 37 |
template = system.file('misc', 'knitr-template.Rnw', package = 'knitr'), |
| 38 |
output = NULL, text = NULL, envir = parent.frame()) { |
| 39 |
lines = if (nosrc <- is.null(text)) read_utf8(script) else split_lines(text) |
| 40 |
# extract title and author from first two lines |
| 41 |
if (comment_to_var(lines[1L], '.knitr.title', '^#+ *title:', envir)) lines = lines[-1L] |
| 42 |
if (comment_to_var(lines[1L], '.knitr.author', '^#+ *author:', envir)) lines = lines[-1L] |
| 43 |
input = basename(template) |
| 44 |
input = with_ext(basename(if (nosrc) script else tempfile()), file_ext(input)) |
| 45 |
txt = read_utf8(template) |
| 46 |
i = grep('%sCHUNK_LABEL_HERE', txt) |
| 47 |
if (length(i) != 1L) stop('Wrong template for stitch: ', template) |
| 48 |
h = sub('CHUNK_LABEL_HERE', '', txt[i]) |
| 49 |
j = grep(.sep.label, lines) |
| 50 |
if (length(j) == 0) { |
| 51 |
lines = c(sprintf(h, 'auto-report'), lines) |
| 52 |
} else { |
| 53 |
lines[j] = sprintf(h, gsub(.sep.label, '\\3', lines[j])) |
| 54 |
if (j[1] != 1L) lines = c(sprintf(h, ''), lines) |
| 55 |
} |
| 56 |
txt[i] = one_string(lines) |
| 57 |
opts_chunk$set( |
| 58 |
fig.align = 'center', par = TRUE, fig.width = 6, fig.height = 6, |
| 59 |
fig.path = paste('figure', gsub('[^[:alnum:]]', '-', input), sep = '/') |
| 60 |
) |
| 61 |
on.exit(opts_chunk$restore(), add = TRUE) |
| 62 |
knit_hooks$set(par = function(before, options, envir) { |
| 63 |
if (before) par(mar = c(4, 4, .1, .1), cex.lab = .95, cex.axis = .9, |
| 64 |
mgp = c(2, .7, 0), tcl = -.3, las = 1) |
| 65 |
}) |
| 66 |
on.exit(knit_hooks$restore(), add = TRUE) |
| 67 |
|
| 68 |
out = knit(input, output, envir = envir, text = txt) |
| 69 |
switch(file_ext(out), tex = { |
| 70 |
tinytex::latexmk(out) |
| 71 |
message('PDF output at: ', with_ext(out, 'pdf')) |
| 72 |
}, md = { |
| 73 |
out.html = with_ext(out, 'html') |
| 74 |
markdown::mark_html(out, out.html) |
| 75 |
message('HTML output at: ', out.html) |
| 76 |
}) |
| 77 |
out |
| 78 |
} |
| 79 |
#' @rdname stitch |
| 80 |
#' @param ... Arguments passed to \code{stitch()}. |
| 81 |
#' @export |
| 82 |
stitch_rhtml = function(..., envir = parent.frame()) stitch( |
| 83 |
..., envir = envir, |
| 84 |
template = system.file('misc', 'knitr-template.Rhtml', package = 'knitr') |
| 85 |
) |
| 86 |
|
| 87 |
#' @rdname stitch |
| 88 |
#' @export |
| 89 |
stitch_rmd = function(..., envir = parent.frame()) stitch( |
| 90 |
..., envir = envir, |
| 91 |
template = system.file('misc', 'knitr-template.Rmd', package = 'knitr') |
| 92 |
) |
| 93 |
|
| 94 |
#' A simple macro preprocessor for templating purposes |
| 95 |
#' |
| 96 |
#' This function expands a template based on the R expressions in \code{{{}}} |
| 97 |
#' (this tag can be customized by the \code{delim} argument). These expressions |
| 98 |
#' are extracted, evaluated and replaced by their values in the original |
| 99 |
#' template. |
| 100 |
#' @param file The template file. |
| 101 |
#' @param ... A list of variables to be used for the code in the template; note that |
| 102 |
#' the variables will be searched for in the parent frame as well. |
| 103 |
#' @param text Character vector of lines of code. An alternative way to specify |
| 104 |
#' the template code directly. If \code{text} is provided, \code{file} will be ignored. |
| 105 |
#' @param delim A pair of opening and closing delimiters for the templating tags. |
| 106 |
#' @return A character vector, with the tags evaluated and replaced by their |
| 107 |
#' values. |
| 108 |
#' @references This function was inspired by the pyexpander and m4 |
| 109 |
#' (\url{http://www.gnu.org/software/m4/}), thanks to Frank Harrell. |
| 110 |
#' @export |
| 111 |
#' @examples # see the knit_expand vignette |
| 112 |
#' if (interactive()) browseVignettes(package='knitr') |
| 113 |
knit_expand = function(file, ..., text = read_utf8(file), delim = c('{{', '}}') ){ |
| 114 |
|
| 115 |
# check if delim is a pair, escaping regex as necessary |
| 116 |
if (length(delim) != 2L) stop('"delim" must be of length 2') |
| 117 |
delim = gsub('([.|()\\^{}+$*?]|\\[|\\])', '\\\\\\1', delim) |
| 118 |
delim = paste0(delim[1L], '((.|\n)+?)', delim[2L]) |
| 119 |
|
| 120 |
txt = one_string(text) |
| 121 |
loc = str_locate(txt, delim)[[1L]] |
| 122 |
if (nrow(loc) == 0L) return(txt) # no match |
| 123 |
mat = str_extract(txt, delim)[[1L]] |
| 124 |
env = list(...) |
| 125 |
env = if (length(env)) list2env(env, parent = parent.frame()) else parent.frame() |
| 126 |
inline_exec(list( |
| 127 |
code = sub(delim, '\\1', mat), code.src = mat, input = txt, location = loc |
| 128 |
), envir = env, hook = identity) |
| 129 |
} |