16
votes

I am trying to write a report in rmarkdown and then use knitr to generate a pdf.

I want all the code to be pushed to the "End of the document", while just displaying results interweaved with my text. The echo='hold' option doesn't do this.

Section of my markdown file

Generate data

```{r chunk1,echo='hold',R.options=}
num_seq<-rnorm(100,0.2)
num_seq
```

We further report the mean of these numbers.  

```{r,echo='hold' }
mean(num_seq)
```

I have tried to read the the relevant documentation found here http://yihui.name/knitr/options/, but I can't figure out how to do this.

1
Does my offered solution answer your question? It is customary to "accept" an answer with the green check mark.r2evans
Yes. Thanks. Slowly getting to know customs here.QuantSolo
Thx! In addition to "thanking the responder," it also provides some closure to the topic (or invites more discussion and revision of the original question).r2evans
This question is very similar to this one.Thomas Reiss

1 Answers

17
votes

I don't think echo='hold' is an option. Regardless, the trick is to use echo=FALSE where the code is included, and then re-use the same chunk name and use eval=FALSE where you want the code to be printed. (Other options in both locations are fine, but these two are the minimum required.)

The following evaluates the code (and optionally includes output from it) where the chunk is located, but doesn't include the code until you specify.

# Header 1

```{r chunk1, echo=FALSE}
x <- 1
x + 5
```

This is a test.

```{r chunk1, eval=FALSE}
```

Results in the following markdown:

Header 1
========

    ## [1] 6

This is a test.

    x <- 1
    x + 5

Edit: I use this frequently in R markdown documents with randomness: I store the random seed in the very beginning (whether I set it manually or just store the current random state for later reproduction) and display it in an annex/appendix:

# Header 1

```{r setseed, echo=FALSE, include=FALSE}
set.seed(seed <- sample(.Machine$integer.max, size=1))
seed
```

This is a test `r seed`.

# Annex A {-}

```{r showsetseed, ref.label='setseed', eval=FALSE}
```

```{r printseed, echo=FALSE}
seed
```

This example doesn't include the results with the original code chunk. Unfortunately, the results aren't stored, and if I set eval=TRUE when I use the same chunk name later, it will calculate and present a different seed. That's why the printseed block. The reason I explicitly "show" seed in the first setseed block is solely so that, in the annex, the showsetseed and printseed chunks flow well. (Otherwise, set.seed does not return a number, so it would have looked wierd.)

BTW: this second example uses ref.label, which Yihui documents here as a more general approach to chunk reuse.

BTW #2: when I said "store the random state", that's not completely correct ... I'm storing a randomly-generated seed. The random state itself is much larger than a single integer, of course. I don't want to anger the PRNG gods :-)