Last active
April 30, 2018 22:12
-
-
Save yihui/2629886 to your computer and use it in GitHub Desktop.
A collection of demos for knitr hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
\documentclass{beamer} | |
\usepackage{url} | |
\begin{document} | |
<<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{} | |
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] | |
<<test>>= | |
library(dlm) | |
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) | |
@ | |
\end{frame} | |
\end{document} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
\documentclass{article} | |
\begin{document} | |
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. | |
<<example-a>>= | |
x = rnorm(4) | |
@ | |
Then we teach b. | |
<<example-b>>= | |
summary(x) | |
@ | |
Yet another example c. | |
<<example-c>>= | |
y = rpois(10, 5) | |
@ | |
And d. | |
<<example-d>>= | |
max(y) | |
@ | |
\end{document} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
\documentclass{article} | |
\begin{document} | |
<<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. | |
<<test>>= | |
1+1 | |
rnorm(30) | |
1:3+1:2 | |
1+'a' | |
@ | |
\end{document} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 <http://yihui.name/knitr/hooks>. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This demo shows you how to check the number of plots produced in a chunk. | |
```{r setup} | |
# 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') | |
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 | |
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
See https://github.com/yihui/knitr-examples/blob/master/012-line-breaks.Rmd |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
See https://github.com/yihui/knitr-examples/blob/master/039-merge.Rmd |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
\documentclass{article} | |
\begin{document} | |
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!' | |
@ | |
\end{document} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
See https://github.com/yihui/knitr-examples/blob/master/013-par.Rnw |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.