# public yihui / knitr-alert.Rnw Last active 2013-03-31

A collection of demos for knitr hooks

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 \documentclass{beamer}\usepackage{url}\begin{document}<>=# do not use the highlight package; will do it manuallyopts_chunk$set(highlight = FALSE, tidy = FALSE)tokens = c('dlmMLE', 'dlmModReg') # a list of words to be highlighted by structure{} knit_hooks$set( 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) x }, output = function(x, options) { x }, error = function(x, options) { paste0('\n', x) })@\title{Insert \textbackslash{}structure and \textbackslash{}alert in Beamer with R code}\author{Yihui Xie} \maketitle \begin{frame}[fragile]These slides show you how to manipulate R code and its output with the knitr package (\url{http://yihui.name/knitr}).  \begin{itemize} \item Rnw source: \url{https://gist.github.com/2629886#file_knitr_alert.rnw} \item PDF output: \url{https://github.com/downloads/yihui/knitr/knitr-alert.pdf}\end{itemize}\end{frame} \begin{frame}[fragile]<>=library(dlm)mleOut <- dlmMLE(Nile, parm = c(0.2, 120), # initial values for optimizer lower = c(1e-7, 0)) # V must be positivemleOut$convergence # always check this!!!x <- matrix(rnorm(10),nc=2)mod <- dlmModReg(x)@\end{frame} \end{document} knitr-checkpoint.Rnw  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 \documentclass{article}\begin{document} This demo shows you an idea of checkpoints'' from Barry Rowlingson. In aworkshop/class, your students may not be able to follow your examples and endup lagging behind others by seven steps. How to help them catch up with theprogress quickly? Hopefully we provide a chunk name and they will be able torestore all the objects up to this chunk. Remember \textbf{knitr} makes a document programmable; you have access andcontrol over chunk options via \texttt{opts\_chunk}. So let's do it. <>=rm(list = ls(all.names = TRUE), envir = globalenv()) opts_chunk$set(cache = TRUE) # enable cache to make it fasteropts_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 checkpointsopts_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. <>=summary(x)@ Yet another example c. <>=y = rpois(10, 5)@ And d. <>=max(y)@ \end{document}
knitr-color-msg.Rnw
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 \documentclass{article}\begin{document}<>=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 thelazy dog the quick brown fox jumps over the lazy dog. <>=1+1rnorm(30)1:3+1:21+'a'@ \end{document} knitr-error.Rmd RMarkdown  1 2 3 4 5 6 7 8 9 10 11 12 13 14 We redefine the error hook so that **knitr** completely stops in case of errors.  {r setup}knit_hooks$set(error = function(x, options) stop(x)) A test case:  {r test}x <- unknown_function(1:10)print(x) See .
knitr-fignum.Rmd
RMarkdown
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 This demo shows you how to check the number of plots produced in a chunk. {r setup}# options$fig.num records the number of plotsknit_hooks$set(fig.num = function(before, options, envir) { if (!before && options$fig.num > 0) { message('\n(*) NOTE: ', options$fig.num, ' plot(s) produced!!\n') NULL }}) Test the hook: {r plot-none}1+1 And this chunk has two plots: {r plot-two}plot(1)plot(3:5) Did you see the message? {r sleep}Sys.sleep(10) # pause 10 secs for you to watch the message
knitr-formatR.Rmd
RMarkdown
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 This demo shows you how to control **formatR** options via chunk hooks. {r setup}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: {r with-comment}1+1 # this comment is preserved {r remove-comment, keep.comment=FALSE}1+1 # this comment is discarded Similarly you can play with other **formatR** options like keep.blank.line. knitr-line-break.Rmd RMarkdown  1 See https://github.com/yihui/knitr-examples/blob/master/012-line-breaks.Rmd knitr-merge.Rmd RMarkdown  1 See https://github.com/yihui/knitr-examples/blob/master/039-merge.Rmd knitr-my-print.Rnw  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 \documentclass{article}\begin{document}Set up a hook to print a character object in bold fonts after the chunk. <>=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: <>=foobar = 'hello, world!'@\end{document}
par.Rnw
 1 See https://github.com/yihui/knitr-examples/blob/master/013-par.Rnw

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.