I want to include code from a specific fragment of one markup document in a second markdown document. I want to do this by accessing a snippet by name (no hacker links to line numbers ). I do not want to run all the code in the child element, because some of them are rather laborious.
Here is what I have tried. We have read_chunk to enable a simple R script in markdown documents. There is run_chunk , but it is unclear whether this can be used with external documents (so far I have been unlucky).
And we can do this to get the whole document with markup to run inside another:
```{r child='first.Rmd'} ```
But how can I get only one specific fragment from a child document into another document? Here is a small example:
This is test-main.Rmd
```{r pick-up-the-kid, child='test-child.Rmd'} ```
And this is test-child.Rmd
Hi, there. I'm a child. ```{r test-child-1} 1+1 dnorm(0) ``` ```{r test-child-2} 2+2 dnorm(0) ```
When we run test-main.Rmd , we get the following:
Hi, there. I'm a child. 1+1
One of the methods that almost does is ref.label . If we edit test-main.Rmd like this:
```{r pick-up-the-kid, child='test-child.Rmd', ref.label='test-child-2'} ```
The output has the only desired fragment, but it is duplicated, which is not good:
Hi, there. I'm a child. 2+2
One solution for duplication is to use eval = FALSE, echo = FALSE in the chunk parameters in the child document:
```{r test-child-2, eval = FALSE, echo = FALSE} 2+2 dnorm(0) ```
which gives the desired result:
2+2
But it is not convenient to change a piece in a child document, since this piece is needed by other pieces in the child document, and I do not want to change with several fragments in the child document each time I start the main document, this is not good for reproducibility.
How can I get only chunk test-child-2 from test-child.Rmd in test-main.Rmd using the link to the chunk name (and without duplicates or messing around with chunk parameters)?
I am looking for a function that can be called by child_chunk , where I can specify the name of the child document and the name chunk and apply the chunk parameters to it in the main document, which are independent of the chunk parameters in the child document.
Or is it the only solution to move the code into R script files and share them between two markdown documents?