Home > Mobile >  Rmarkdown: How to use code chunk from other Rmd file
Rmarkdown: How to use code chunk from other Rmd file

Time:01-25

How to use code chunk from child document in another Rmd file? I have one parent document named figures.Rmd which have following structure


`{r child='force.Rmd',echo=F,ref.label='pressure'}
`


some text 
`{r child='force.Rmd',echo=F,ref.label='cars'}

and the child document named force.Rmd which have following structure

`{r, cars,echo=F}
options(knitr.duplicate.label = 'allow')

plot(cars)
`



`{r, pressure,echo=F}
options(knitr.duplicate.label = 'allow')

summary(pressure)
`

I want to read some chunks from the force.Rmd in the figures.Rmd. I am getting some output but it is producing the output 2 times. So basically I have 2 or 3 chunks in force.Rmd which I want to use at different places in figures.Rmd . How can I do that without getting the output 2 times?

CodePudding user response:

This is parent.Rmd:

---
title: "parent"
author: "Me"
date: "2023-01-25"
output: html_document
---

## Parent

This is parent 

## Some part of child 

```{r echo=FALSE}
library(knitr)
invisible(knitr::purl("child.Rmd", output="temp", quiet=TRUE))
read_chunk("temp")
```

```{r ref.label='cars'}
```

## Some text

Here I am.

## Some other part of child

## Some part of child 

```{r ref.label='pressure'}
```

```{r echo=FALSE}
unlink("temp")
```

This is child.Rmd

```{r cars}
summary(cars)
```

```{r pressure}
plot(pressure)
```

I can call each single child chunk at various positions:

enter image description here

  • Related