Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create appendix with R-code in rmarkdown/knitr

Is it possible to get all of the code in a appendix. Say I have two chunks in a document and then some text.

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

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

Above is Y output.

And then I want all of the code in a appendix but shown as if I put eval=FALSE in the chunk.

Something like this

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

Expected output:

Chunk_1
x <- 4+5  
x

Chunk_2  
y <- 22+325  
y
like image 752
TKN Avatar asked Nov 02 '15 20:11

TKN


People also ask

How do you add R code to R Markdown?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).

How can you compile the R Markdown document using knitr package?

The usual way to compile an R Markdown document is to click the Knit button as shown in Figure 2.1, and the corresponding keyboard shortcut is Ctrl + Shift + K ( Cmd + Shift + K on macOS). Under the hood, RStudio calls the function rmarkdown::render() to render the document in a new R session.

How does R knitr work?

When you run render , R Markdown feeds the . Rmd file to knitr, which executes all of the code chunks and creates a new markdown (. md) document which includes the code and its output. The markdown file generated by knitr is then processed by pandoc which is responsible for creating the finished format.

Can you run code in R Markdown?

You can open it here in RStudio Cloud. or by typing the chunk delimiters ```{r} and ``` . When you render your . Rmd file, R Markdown will run each code chunk and embed the results beneath the code chunk in your final report.


2 Answers

Another possibility:

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

as suggested by Yihui's nice example

like image 148
Will Townes Avatar answered Sep 28 '22 06:09

Will Townes


knitr::purl() can extract all R code from a markdown file into an R script. You can add that as an appendix.

## appendix

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

```
like image 40
Thierry Avatar answered Sep 28 '22 08:09

Thierry