Search code examples
r-markdownknitrbookdown

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


Imagine a simplified bookdown/rmarkdown document that goes something like this:

---
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.

In such a report I am aiming to replace the <!-- Placeholder - See question --> bit with an "Executive Summary"/"Sneak-Peak" section, that centers on the graphical output of chunk data-plot. Is that achievable in bookdown/rmarkdown/knitr while maintaining the code/narrative integration given the relative positioning?


Solution

  • Yes, you can use knitr::fig_chunk() to dynamically retrieve the path to a figure produced in a specific code chunk, e.g.,

    ---
    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

    To make this work for other types of output formats, you may need to change the filename extension pdf. One way to do it can be:

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

    Of course, this assumes that you use the pdf device for LaTeX/PDF output formats, and use png for other formats (which are the default settings for graphical devices in R Markdown).