bookdown/rmarkdown/knitr: 打开一个包含后面代码块的(图形)结果的文档?

bookdown/rmarkdown/knitr: Open a document with the (graphical) result of a later code chunk?

想象一个简化的 bookdown/rmarkdown 文档,内容如下:

---
title: "Test Doc"
author: "Balin"
date: "May 25, 2018"
output: 
  bookdown::pdf_document2:
    toc: no
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

<!-- Placeholder - See question -->

This stands in for an extensive report where `code`, its documentation
and interpretation of its results are integrated:

1. We load some data:
   ```{r data-loading}
    my_data <- cars
   ```

2. We (rougly) explore that data and report on it:
   ```{r data-exploration}
   summary(my_data)
   ```

3. We transform the data:
   ```{r data-transform}
   my_data <- log2(my_data)
   ```

4. ... many, many more steps ...

5. We perform a (central) graphical analysis:
   ```{r data-plot}
   plot(my_data)
   ```

6. We state some interpretation ... etc.

在这样的报告中,我打算用 "Executive Summary"/"Sneak-Peak" 部分替换 <!-- Placeholder - See question --> 位,该部分以块 data-plot 的图形输出为中心。这是否可以在 bookdown/rmarkdown/knitr 中实现,同时在相对定位的情况下保持 code/叙事整合?

是的,您可以使用 knitr::fig_chunk() 动态检索特定代码块中生成的图形的路径,例如,

---
title: "Test Doc"
author: "Balin"
date: "May 25, 2018"
output: 
  bookdown::pdf_document2:
    toc: no
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Executive Summary {-}

Here is an amazing discovery!

![](`r knitr::fig_chunk('data-plot', 'pdf')`)

# Detailed analysis

This stands in for an extensive report where `code`, its documentation
and interpretation of its results are integrated:

1. We load some data:
   ```{r data-loading}
    my_data <- cars
   ```

2. We (rougly) explore that data and report on it:
   ```{r data-exploration}
   summary(my_data)
   ```

3. We transform the data:
   ```{r data-transform}
   my_data <- log2(my_data)
   ```

4. ... many, many more steps ...

5. We perform a (central) graphical analysis:
   ```{r data-plot}
   plot(my_data)
   ```

6. We state some interpretation ... etc.

要使其适用于其他类型的输出格式,您可能需要更改文件扩展名 pdf。一种方法可以是:

![](`r knitr::fig_chunk('data-plot', if (knitr::is_latex_output()) 'pdf' else 'png')`)

当然,这假设您将 pdf 设备用于 LaTeX/PDF 输出格式,并将 png 用于其他格式(这是 R 中图形设备的默认设置降价)。