Evaluate code chunks in Rmd in different order

Viewed 94

I have a code chunk "data_prep" which is included at the end of my Rmd file, but I'd like to show its result right at the beginning (after headline 1). The problem is that code chunk "data_prep" needs to run before the chunk named "data_summary" (data_summary depends on data_prep).

How can i change the order in which the code chunks are being evaluated?

---
title: "Untitled"
output: html_document
---

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

```{r}
library(dplyr)
```

# 1

```{r data_summary, ref.label='data_prep'}
```

# 2

```{r}
df_1 <- mtcars %>% sample_n(10)
```

# 3

```{r data_prep, results='hide'}
mtcars_summary <- df_1 %>% 
  group_by(cyl) %>% 
  summarise(hp_avg = mean(hp))

mtcars_summary
```

I have also tried the following two variants:

```{r data_prep, echo = TRUE}
```

and

```{r data_summary, dependson='data_prep'}
```
1 Answers

That's not how dependson works. It's used to specify code chunks that chunk depends on, so that if cached, it's updated when those dependencies are updated. However, RMarkdown has a way to use the cache to do just what you want. We can cache any chunk and call that in an earlier chunk, if we desire. With just the two relevant chunks from your example amended (the rest untouched), we can do:

```{r data_summary}
knitr::load_cache("data_prep", "mtcars_summary")
```
## # A tibble: 3 × 2
##     cyl hp_avg
##   <dbl>  <dbl>
## 1     4   84.3
## 2     6  116. 
## 3     8  191

```{r data_prep, results = "hide", cache = TRUE}
mtcars_summary <- df_1 %>% 
  group_by(cyl) %>% 
  summarise(hp_avg = mean(hp))

mtcars_summary
```
Related