Skip to content
Create a gist now

Instantly share code, notes, and snippets.

A collection of demos for knitr hooks
<<setup, include=FALSE, tidy=FALSE, highlight=FALSE>>=
# do not use the highlight package; will do it manually
opts_chunk$set(highlight = FALSE, tidy = FALSE)
tokens = c('dlmMLE', 'dlmModReg') # a list of words to be highlighted by structure{}
chunk = function(x, options) {
x = strsplit(x, '\n')[[1]] # split into lines
idx = grep('^(.*)(#.*)$', x)
for (i in seq_along(idx)) {
# put all comments in alert{}
x[idx[i]] = gsub('^([^#]*)(.*)$', sprintf('\\1\\\\alert<%d>{\\2}', i), x[idx[i]])
x = paste0(x, collapse = '\n') # merge lines into one string
# put all output in the semiverbatim environment
paste0('\\begin{semiverbatim}', x, '\\end{semiverbatim}')
source = function(x, options) {
for (i in tokens) x = gsub(i, paste0('\\structure{', i, '}'), x, fixed = TRUE)
output = function(x, options) {
error = function(x, options) {
paste0('\n', x)
\title{Insert \textbackslash{}structure and \textbackslash{}alert in Beamer with R code}
\author{Yihui Xie}
These slides show you how to manipulate R code and its output with the knitr package (\url{}).
\item Rnw source: \url{}
\item PDF output: \url{}
mleOut <- dlmMLE(Nile,
parm = c(0.2, 120), # initial values for optimizer
lower = c(1e-7, 0)) # V must be positive
mleOut$convergence # always check this!!!
x <- matrix(rnorm(10),nc=2)
mod <- dlmModReg(x)
This demo shows you an idea of ``checkpoints'' from Barry Rowlingson. In a
workshop/class, your students may not be able to follow your examples and end
up lagging behind others by seven steps. How to help them catch up with the
progress quickly? Hopefully we provide a chunk name and they will be able to
restore all the objects up to this chunk.
Remember \textbf{knitr} makes a document programmable; you have access and
control over chunk options via \texttt{opts\_chunk}. So let's do it.
<<setup, include=FALSE>>=
rm(list = ls(all.names = TRUE), envir = globalenv())
opts_chunk$set(cache = TRUE) # enable cache to make it faster
opts_chunk$set(eval = TRUE, echo = TRUE, include = TRUE)
knit_hooks$set(checkpoint = function(before, options, envir) {
# e.g. we skip all chunks after the chunk example-b
if (!before && options$label == options$checkpoint) {
opts_chunk$set(cache = FALSE, eval = FALSE, echo = FALSE, include = FALSE)
# you can do other things like dumping `envir` into globalenv(), e.g.
# assign('ChunkEnv', envir, envir = globalenv())
## set checkpoint=NULL to disable checkpoints
opts_chunk$set(checkpoint = 'example-b') # restore objects up to exmple-b
## now if you knit() this document, only x exists; y is not loaded
Now we teach example a.
x = rnorm(4)
Then we teach b.
Yet another example c.
y = rpois(10, 5)
And d.
<<setup, include=FALSE>>=
options(width = 60)
color_block = function(color) {
function(x, options) sprintf('{\\color{%s}\\begin{verbatim}%s\\end{verbatim}}',
color, x)
knit_hooks$set(warning = color_block('magenta'),
error = color_block('red'))
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.

We redefine the error hook so that knitr completely stops in case of errors.

knit_hooks$set(error = function(x, options) stop(x))

A test case:

x <- unknown_function(1:10)


This demo shows you how to check the number of plots produced in a chunk.

# options$fig.num records the number of plots
knit_hooks$set(fig.num = function(before, options, envir) {
  if (!before && options$fig.num > 0) {
    message('\n(*) NOTE: ', options$fig.num, ' plot(s) produced!!\n')

Test the hook:


And this chunk has two plots:


Did you see the message?

Sys.sleep(10) # pause 10 secs for you to watch the message

This demo shows you how to control formatR options via chunk hooks.

knit_hooks$set(keep.comment = function(before, options, envir) {
  if (before) options(keep.comment = options$keep.comment)
opts_chunk$set(keep.comment = TRUE) # default chunk option is TRUE

See if it works:

1+1 # this comment is preserved
1+1 # this comment is discarded

Similarly you can play with other formatR options like keep.blank.line.

Set up a hook to print a character object in bold fonts after the chunk.
<<setup, include=FALSE>>=
knit_hooks$set(my_print = function(before, options, envir) {
if (!before) sprintf('print object %s as \\textbf{%s}',
options$my_print, get(options$my_print, envir = envir))
Test the hook:
<<test-print, my_print='foobar'>>=
foobar = 'hello, world!'

Hi Yihui--

Thanks for all of your work on this. Question: I'm assembling slides for an R intro course, and I want the R input and output to look exactly like it does on the screen. So far, I found the highlight=FALSE and comment=NA chunk options, which are working fine for me. My problem is that the red error messages still appear. (I had thought they would go away with the highlight=FALSE.) I tried the hook above (knitr-color-msg.Rnw) but with that, I get latex errors. Apologies if this is an idiotic question. Can you help?

Ken K.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.