Prevent knitr / Rmarkdown from striping code snippet

When I use knitr to create an HTML document from the following code:

Chunk Output ======================================================== Outside a chunk. ```{r chunk1, results='asis'} cat('Inside a chunk\n\n') for (i in 1:3) { cat('* Inside loop #', i, '\n') } cat('Outside a loop, but still inside the first chunk') ``` Between chunks. ```{r chunk2, results='asis'} cat('Inside second chunk') ``` 

I get output where the code in chunk1 alternates with the output of the cat statements. Interestingly, the output in a for loop is output as a single block.

I would prefer to display all the code from chunk1 , and then all the output from chunk1 . Is there a way to ask Rmarkdown / knitr to avoid the more granular weave it is doing now?

+6
source share
1 answer

Here is the solution I suggested

 Chunk Output ======================================================== Outside a chunk. ```{r chunk1, results='hide'} cat('Inside a chunk\n\n') for (i in 1:3) { cat('* Inside loop #', i, '\n') } cat('Outside a loop, but still inside the first chunk') ``` ```{r ref.label = 'chunk1', results = 'asis', echo = F} ``` 

In the latest version, knitr @yihui added a new option chunk results = "hold" , which automatically keeps printing all output to the end. Accordingly, we can simply write

 Chunk Output ======================================================== Outside a chunk. ```{r chunk1, results='hold'} cat('Inside a chunk\n\n') for (i in 1:3) { cat('* Inside loop #', i, '\n') } cat('Outside a loop, but still inside the first chunk') ``` 
+8
source

Source: https://habr.com/ru/post/952763/


All Articles