Debian Codegraph @

inst/doc/knit_expand.Rmd

raw
1 ---
2 title: Templating with knit_expand()
3 author: Yihui Xie
4 date: "`{r} Sys.Date()`"
5 output:
6 html:
7 meta:
8 css: ["@default"]
9 ---
10
11 <!--
12 %\VignetteEngine{litedown::vignette}
13 %\VignetteIndexEntry{Templating with knit_expand()}
14 -->
15
16 A few simple examples:
17
18 ```{r}
19 library(knitr)
20 knit_expand(text = 'The value of pi is {{pi}}.')
21 knit_expand(text = 'The value of a is {{a}}, so a + 1 is {{a+1}}.', a = rnorm(1))
22 knit_expand(text = 'The area of a circle with radius {{r}} is {{pi*r^2}}', r = 5)
23 ```
24
25 Any number of variables:
26
27 ```{r}
28 knit_expand(text = 'a is {{a}} and b is {{b}}, with my own pi being {{pi}} instead of {{base::pi}}', a=1, b=2, pi=3)
29 ```
30
31 Custom delimiter `<% %>`:
32
33 ```{r}
34 knit_expand(text = 'I do not like curly braces, so use % with <> instead: a is <% a %>.', a = 8, delim = c("<%", "%>"))
35 ```
36
37 The pyexpander delimiter:
38
39 ```{r}
40 knit_expand(text = 'hello $(LETTERS[24]) and $(pi)!', delim = c("$(", ")"))
41 ```
42
43 Arbitrary R code:
44
45 ```{r}
46 knit_expand(text = 'you cannot see the value of x {{x=rnorm(1)}}but it is indeed created: x = {{x}}')
47 res = knit_expand(text = c(' x | x^2', '{{x=1:5;paste(sprintf("%2d | %3d", x, x^2), collapse = "\n")}}'))
48 cat(res)
49 ```
50
51 The m4 example: <https://en.wikipedia.org/wiki/M4_(computer_language)>
52
53 ```{r}
54 res = knit_expand(text = c('{{i=0;h2=function(x){i<<-i+1;sprintf("<h2>%d. %s</h2>", i, x)} }}<html>',
55 '{{h2("First Section")}}', '{{h2("Second Section")}}', '{{h2("Conclusion")}}', '</html>'))
56 cat(res)
57 ```
58
59 Build regression models based on a template; loop through some variables in `mtcars`:
60
61 ```{r, comment=''}
62 src = lapply(names(mtcars)[2:5], function(i) {
63 knit_expand(text=c("# Regression on {{i}}", '```{r lm-{{i}}}', 'lm(mpg~{{i}}, data=mtcars)', '```', ''))
64 })
65 # knit the source
66 litedown::fuse(unlist(src), 'markdown')
67 ```