-
Notifications
You must be signed in to change notification settings - Fork 586
/
045-chunk-hook.Rmd
85 lines (63 loc) · 1.63 KB
/
045-chunk-hook.Rmd
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# Three arguments in chunk hooks
A chunk hook has three arguments: `before`, `options` and `envir`. We show how they work through some simple examples.
## The `before` argument
It is a logical argument: `before == TRUE` executes code before a chunk.
```{r}
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:
```{r foo1='whatever'}
1+1
```
## The `options` argument
It contains all the chunk options (include global options) for the current chunk.
```{r}
knit_hooks$set(foo2 = function(before, options, envir) {
if (!before) {
z = capture.output(str(options[c('eval', 'dev', 'results', 'bar1', 'bar2', 'bar3')]))
z = paste(' ', z, sep = '', collapse = '\n')
paste('Some chunk options in the above chunk are:\n\n', z, sep = '')
}
})
```
Test the `foo2` hook:
```{r foo2='hi', bar1=TRUE, bar2='asdf', bar3=3.14159}
1+1
```
## The `envir` argument
It is the environment of the current chunk.
```{r}
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:
```{r foo3=TRUE}
x2=1+1; y3=rnorm(10)
```
Another example:
```{r}
knit_hooks$set(foo4 = function(before, options, envir) {
if (!before && exists('z5', envir = envir)) {
sprintf('**Ha! I see z5 = %.3f!**', envir$z5)
}
})
```
Test `foo4`:
```{r foo4='qwer'}
pi
```
This above chunk is quiet because `z5` does not exist yet.
```{r foo4='asdf'}
z5=2*pi
```