When knitr
processes a document, the document is split into two categories of input: ordinary text and code chunks. Ordinary text stays unchanged and is passed to the output file. Consequently, if plain text is supposed to be included dynamically, it must be inside a chunk.
Code chunks are evaluated according to their options. In the current scenario, to most important options are:
eval
determines whether a chunk is evaluated; eval = FALSE
skips the chunk. echo
determines whether to source code of the chunk is displayed. results
determines how the output of a chunk is treated. By default (results = "markup
) a output hook is used to apply document-type-specific markup to the output. results = "asis"
means that all output is included in the output file "as-is", without any modifications.
With these three options, the following could be accomplished:
This is some text ...
```{r, echo = FALSE, eval = FALSE, results = "asis"}
cat("... with a secret inside ...")
```
```{r, echo = FALSE, eval = TRUE, results = "asis"}
cat("... that is dynamically generated.")
```
Output:
This is some text ...
... that is dynamically generated.
Note that the first chunk is not evaluated because eval = FALSE
.
However, it is cumbersome to cat()
lots of text from a R chunk. engine
can be used to overcome this. Besides R, there are other engines that can be used to evaluate chunks, among them the (currently undocumented?) engine asis
. This engine is very simple. From the knitr
NEWS file:
added a new engine named asis
to write the chunk content without processing it; it also respects the chunk options echo
and eval
-- when either one is FALSE
, the chunk will be hidden; this makes it possible to write text conditionally
Combining the asis
engine with the following syntactic sugar (source)
for language engines, the syntax of R Markdown code chunk headers can be ```{lang, option=value}`
now (e.g. ```{python}
and ```{Rcpp}
), which is equivalent to ```{r, engine='lang', option=value}
the example from above becomes:
This is some text ...
```{asis, echo = FALSE}
... with a secret inside ...
```
```{asis, echo = TRUE}
... that is dynamically generated.
```