R Markdown - A brief description of all the code fragments used in the document.

I write a report in R Markdown in which I do not want to print any of my R-code in the main part of the report - I just want to show graphs, calculate the variables that I insert in the inline text, and sometimes show a small amount of raw R output . So I am writing something like this:

In the following plot, we see that blah blah blah:
```{r snippetName, echo=F}
plot(df$x, df$y)
```

Now...

This is all good and good. But I would also like to provide an R-code at the end of the document so that anyone is curious to see how it was created. Right now I have to manually write something like this:

Here is snippet 1, and a description of what section of the report
this belongs to and how it used:
```{r snippetName, eval=F}
```
Here is snippet 2:
```{r snippetTwoName, eval=F}
```
<!-- and so on for 20+ snippets -->

, . , ? , - :

```{r snippetName, echo=F, comment="This is snippet 1:"}
# the code for this snippet
```

- , :

This is snippet 1:
```{r snippetName, eval=F}
```

, - - .Rmd, - (, , - , pandoc?), , - .

. , , . , , , ( , ?). 20+ .

+4
2

, knitr, , pandoc pandoc . Rmd echo=TRUE, , , .

, R ( , pandoc), ( ) . . , python (, haskell , ). Rmd, R- . , placeholder CodeBlock lastchunk.

, postpone_chunks.py.

#!/usr/bin/env python

from pandocfilters import toJSONFilter, Str, Para, CodeBlock

chunks = []


def postpone_chunks(key, value, format, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "r" in classes:
            chunks.append(CodeBlock([ident, classes, keyvals], code))
            return Para([Str("")])
        elif code == 'lastchunk':
            return chunks

if __name__ == "__main__":
    toJSONFilter(postpone_chunks)

knitr pandoc_args. , .

---
title: A test
output:
  html_document: 
    pandoc_args: ["--filter", "postpone_chunks.py"]
---

Here is a plot.

```{r}
plot(iris)
```

Here is a table.

```{r}
table(iris$Species)
```

And here are the code chunks used to make them:

    lastchunk

, haskell, . , .

+2

knitr, pandoc. , Yihui https://github.com/yihui/knitr-examples/blob/master/073-code-appendix.Rnw

echo=FALSE : opts_chunk$set(echo = FALSE)

, :

 ```{r show-code, ref.label=all_labels(), echo = TRUE, eval=FALSE}

 ```

. ; , - ... (, ).

: , , : ref.label = all_labels(!exists('engine')) - . 40919201

+3

Source: https://habr.com/ru/post/1629608/


All Articles