A chunk hook has three arguments: before
, options
and envir
. We show how they work through some simple examples.
before
argumentIt is a logical argument: before == TRUE
executes code before a chunk.
library(knitr) knit_hooks$set(foo1 = function(before, options, envir) { if (before) { '_I appear before a chunk!_\n\n' } else { '\n\n_I am after a chunk..._' } })
Test the foo1
hook:
1+1
options
argumentIt contains all the chunk options (include global options) for the current chunk.
knit_hooks$set(foo2 = function(before, options, envir) { if (!before) { z = capture.output(str(options[c('eval', 'dev', 'results', 'bar1', 'bar2', 'bar3','label')])) z = paste(' ', z, sep = '', collapse = '\n') paste('Some chunk options in the above chunk are:\n\n', z, sep = '') } })
Test the foo2
hook:
1+1
envir
argumentIt is the environment of the current chunk.
knit_hooks$set(foo3 = function(before, options, envir) { if (!before) { paste('Objects available in the above chunk:', paste('`', ls(envir), '`', sep = '', collapse = ', ')) } })
Test the foo3
hook:
x2=1+1; y3=rnorm(10)
Another example:
knit_hooks$set(foo4 = function(before, options, envir) { if (!before && exists('z5', envir = envir)) { sprintf('**Ha! I see z5 = %.3f!**', envir$z5) } })
Test foo4
:
pi
This above chunk is quiet because z5
does not exist yet.
z5=2*pi
We want to use chunk-hooks to convert graphics from a given format, like LibreOffice-Draw into pdf or png which can be included in documents.
knit_hooks$set(conv.odg = function(before, options, envir) { if (is.null(options$label)) stop(" *** ERROR: chunk must be labelled\n") if (is.null(options$odg.path)){ odg.path <- "odg" } else { odg.path <- options$odg.path } odg.fname <- paste(options$label, "odg", sep = ".") odg.fig.src <- file.path(odg.path, odg.fname) trg.fig <- paste(options$label, "pdf", sep = ".") if (before) { if (!file.exists(odg.fig.src)) rmddochelper::create_odg_graphic(psGraphicName = odg.fname, psGraphicPath = odg.path) if (!file.exists(trg.fig) | !options$odg.graph.cache) rmddochelper:::convertLibOToGraphic(psLibOFile = odg.fname, psOutFormat = "pdf", psLibODir = odg.path) } })
Now we create a chunk that includes a figure
knitr::include_graphics(path = "FigInclude.pdf")
This is the first line after the figure inclusion.
Sys.time() sessionInfo()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.