4

UPDATE: Seems like my question is actually a very near duplicate of this question and according to that thread, there is currently no "easy" solution. However, that question is over a year old now, and the time may have changed (one can hope!).

My original question follows:


I'm thinking that I need some kind of mechanism to re-order the text and or R chunks in the document as it is being knit. What I want to be able to do is to write an "article" style document with an abstract and summary at the beginning, before I get into any R code, but that contains "forward"-references to things that will be calculated in the R code.

So my exec summary at the beginning might be

We found a `r final_correlation/100`% correlation between x and y...
but "final_correlation" will be calculated at the back end of the document as I go through all of the steps of the reproducible research.

Indeed, when I read about reproducible research, I often see comments that the documentation can often be better presented out-of programming sequence.

I believe that in other literate programming frameworks the chunks can be tangled into a different order from that in which they were presented. How can I achieve that in knitr? Or is there some other completely different workflow or pattern I could adopt to achieve the outcome I want?

Community
  • 1
  • 1
dsz
  • 4,542
  • 39
  • 35

1 Answers1

1

There is no way to define the order to evaluate all the code chunks in knitr at the moment. One idea I can think of is to write the abstract in the end of the article, and include it in the beginning. An outline:

  • article.Rmd
  • abstract.Rmd

In article.Rmd:

Title.

Author.

Abstract.

```{r echo=FALSE, results='asis'}
if (file.exists('abstract.md')) {
  cat(readLines('abstract.md'), sep = '\n')
} else {
  cat('Abstract not ready yet.')
}
```

More code chunks.

```{r}
x <- 1:10
y <- rnorm(10)
final_correlation <- cor(x, y)
```

Body.

```{r include=FALSE}
knitr::knit('abstract.Rmd')  # generates abstract.md
```

In abstract.Rmd:

We found a `r final_correlation/100`% correlation between x and y...
Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • I get that this is a great way for keeping the DRY principle in the current way that `knitr` works. I had been hoping for a one-file solution. And I have my answer for today, thank you! – dsz Oct 14 '14 at 21:23