bookdown / rmarkdown / knitr:打开一个带有后续代码块(图形)结果的文档?

时间:2018-05-25 07:44:56

标签: r-markdown knitr bookdown

想象一下简化的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.

在这样的报告中,我的目标是将<!-- Placeholder - See question -->位替换为&#34;执行摘要&#34; /&#34; Sneak-Peak&#34; section,以chunk data-plot的图形输出为中心。这可以在bookdown / rmarkdown / knitr中实现,同时保持code /叙事整合给定相对定位吗?

1 个答案:

答案 0 :(得分:2)

是的,您可以使用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 output

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

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

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