2

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?

Maël
  • 45,206
  • 3
  • 29
  • 67
Andrew
  • 111
  • 4

1 Answers1

1

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.
Maël
  • 45,206
  • 3
  • 29
  • 67
  • 1
    That is brilliant. Many thanks Yihui. I ended up creating an .Rda file from the first markdown file to save my variables, then loading them into the 2nd markdown file. But this is so much easier! – Andrew Jan 21 '22 at 09:46
  • I just realised that the above solution won't work for me because the output for the two .Rmd files is in different formats (html and docx respectively). As a workaround I have created an .Rda file with the vars I require from the first .Rmd, then loading them into the 2nd .Rmd file. It is a bit clunky but works. I gather there is not a more concise solution if the outputs are of a different format? – Andrew Jan 21 '22 at 09:59
  • Good to know. For me, the first solution (with knit_child) works on any output format. The second solution (with `child` in the chunk) results in the text from the first file being displayed as well in the second. – Maël Jan 21 '22 at 10:21
  • You are correct Mael. When I use the first solution in this example I get the correct output. In my complicated code, I needed to add to the YAML "always_allow_html: true". Now when I run this code I get an error "Error in setwd(opts_knit$get("output.dir")) : character argument expected". The message output states that I can use "quiet=TRUE" in the chunk. However this doesn't work. – Andrew Jan 21 '22 at 13:57
  • 1
    I added Mat Dancho's solution and it worked. No more messages. https://stackoverflow.com/questions/20060518/in-rstudio-rmarkdown-how-to-setwd – Andrew Jan 21 '22 at 14:03