When knitr processes a document, the document is divided into two input categories: plain text and code fragments. Plain text remains unchanged and transferred to the output file. Therefore, if plain text should be included dynamically, it should be inside the fragment.
Code fragments are evaluated according to their options . In the current scenario, the most important parameters are:
eval determines whether a piece is evaluated; eval = FALSE skips the piece. echo determines whether the source code of the fragment is displayed. results determines how the output of the piece is processed. By default ( results = "markup ), the output hook is used to apply document type markup for output. results = "asis" means that all output is included in the" as-is "output file without any changes.
With these three options, you can do the following:
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.
Please note that the first fragment is not evaluated, because eval = FALSE .
However, cumbersome cat() can use a lot of text from the R. engine fragment to overcome this. In addition to R, there are other engines that can be used to evaluate chunks, including the engine (currently undocumented?) asis . This engine is very simple. From the knitr NEWS file :
added a new engine called asis to record the contents of a fragment without processing it; it also takes into account the chunk echo and eval parameters - if one of them is FALSE , the fragment will be hidden; this allows you to write text conditionally
Combining the asis engine with the following syntactic sugar ( source )
for language engines, the syntax for the headers of R Markdown code blocks can now be ```{lang, option=value}` (for example, ```{python} ```{Rcpp} ), which is equivalent ```{Rcpp} ```{r, engine='lang', option=value}
example above:
This is some text ... ```{asis, echo = FALSE} ... with a secret inside ... ``` ```{asis, echo = TRUE} ... that is dynamically generated. ```