Accessing objects from another mardown file

Viewed 287

I have generated a report using rmarkdown. I would like to generate a second report using variables I created within the first rmarkdown file. For instance, say my first document is :

---
output: html_document
---

```{r variables, include=FALSE}
y <- 10
```

This is text.

Now I would like my second document to print "The value of y is 10" . The code that doesn't work is :

---
output: word_document
---

The value of y is `r y`

How do I get access to the y variable created in my 1st document for use in my 2nd document?

1 Answers

Use knitr::knit_child() or (equivalently) the child option in a chunk and set to include = FALSE.

file2.Rmd:

---
output: word_document
---

```{r include=FALSE}
knitr::knit_child("file1.Rmd")
```

The value of y is `r y`

enter image description here

Or file2.Rmd (however in this solution, text output is also displayed):

---
output: html_document
---

```{r, child="file1.Rmd", include=FALSE}
```

The value of y is `r y`

Then file1.Rmd:

---
output: html_document
---

```{r variables, include=FALSE}
y <- 10
```

This is text.
Related