prevent knitr/Rmarkdown from interleaving chunk output with code

核能气质少年 提交于 2019-12-22 05:00:28

问题


When I use knitr to build an HTML document out of 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 is interleaved with the output of the cat statements. Interestingly, the output within the for loop is output as a single block.

I would prefer to have all of the code from chunk1 to appear first, followed by all of the output from chunk1. Is there a way to ask Rmarkdown/knitr to avoid the more granular interweaving that it's currently doing?


回答1:


Here is the solution I proposed

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 of knitr, @yihui has added a new chunk option results = "hold", which automatically holds printing of all output to the end. Accordingly, we can just 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')
```


来源:https://stackoverflow.com/questions/18517293/prevent-knitr-rmarkdown-from-interleaving-chunk-output-with-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!