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