r markdown输出为pdf:停止将代码块分解

Dan*_*lle 2 pdf plot r r-markdown

我正在将r markdown文件打印为pdf。我尝试了各种输出规格,但是该图始终显示在段[1]和[2]的中间。

我希望所有代码都显示为一个块,稍后将在文档中调用该图。

```{r, include=TRUE, results='hide'}
# [1] There is code up here

# [plot interrupts the code chunk here] Scatter plot

plot1 = plot(df$var1, df$var)

# [2] More code below this point
```
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 6

使用chunk选项fig.show = 'hold'可在该块的末尾显示该块所产生的所有绘图。这是一个示例.Rmd文件和输出。

---
title: Stop Plot Breakikng Up Code Chunk
output: pdf_document
---

The key is to use the chunk option `fig.show = 'hold'` so that all plots from
the chunk will will displayed at the end of the chunk.

```{r setup, include = FALSE, cache = FALSE}
library(knitr)
opts_chunk$set(fig.show = "hold")
```

We'll use the `mtcars` data set for the example.

```{r plot1, include = TRUE, results = "hide"}
mean(mtcars$wt)
mean(mtcars$mpg)

plot(mtcars$wt, mtcars$mpg)

var(mtcars$wt)
```

End of example.
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

编辑:

另一个解决方案,更接近我想您正在寻找的解决方案,是ref.label用于重用代码块。

---
title: Stop Plot Breaking Up Code Chunk
output: pdf_document
---

The key is to use the chunk option `fig.show = 'hold'` so that all plots from
the chunk will will displayed at the end of the chunk.

```{r setup, include = FALSE, cache = FALSE}
library(knitr)
opts_chunk$set(fig.show = "hold",
               collapse = TRUE)
```

We will use the `mtcars` data set for the example.

```{r all_code}
```{r mean_code, ref.label = "means", echo = TRUE, results = "hide"}
```{r plot1_code, ref.label = "plot1", echo = TRUE, fig.show = "hide", fig.keep = "none"}
```{r var_code, ref.label = "var_wt", echo = TRUE, results = "hide"}
```


Description of a plot

```{r "plot1", echo = FALSE}
plot(mtcars$wt, mtcars$mpg)
```

More text.

Below here, chunks that are evaluated, but not shown.

```{r means, include = FALSE}
mean(mtcars$wt)
mean(mtcars$mpg)
```

```{r var_wt, include = FALSE}
var(mtcars$wt)
```

End of the example.
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明