在 rmarkdown/knitr 中使用 R 代码创建附录

Create appendix with R-code in rmarkdown/knitr

是否可以在附录中获取所有代码。假设我在文档中有两个块,然后是一些文本。

```{r, echo=TRUE}
x <- 4+5
x
```  
Above is X output.

```{r, echo=TRUE}
y <- 22+325
y
```   

Above is Y output.

然后我想要附录中的所有代码,但显示为好像我将 eval=FALSE 放在块中。

像这样

```{r, SHOW_ALL_CODE=TRUE}
```

预期输出:

Chunk_1
x <- 4+5  
x

Chunk_2  
y <- 22+325  
y

knitr::purl()可以将markdown文件中的所有R代码提取到R脚本中。您可以将其添加为附录。

## appendix

```{r code=readLines(knitr::purl('~/path/to/file.Rmd', documentation = 0)), eval = FALSE}

```

您可以使用对初始块的引用,但随后更改选项:

main text

```{r blah, echo = FALSE}
summary(cars)
```

appendix

```{r blah2, ref.label='blah', eval = FALSE}
```

这将给出:

另一种可能性:

### Appendix 
```{r, ref.label=knitr::all_labels(),echo=TRUE,eval=FALSE}
```

根据Yihui's nice example

的建议