How to reuse R Markdown excerpts in new Markdown documents

Hi all,

I have a possibly weird question: I'm writing two different R Markdown documents in the same R Studio project (which I can link here if needed, it's on RStudio Cloud). One uses a certain approach, let's call it data_driven_report.rmd, and another one uses a different approach, let's call it first_principles_based_report.rmd. Both reports have a section called Background which is exactly the same. Having a duplicate section in both documents doesn't make sense, for the usual reasons why we don't duplicate code across projects. Thus I would like to move this section to a background.Rmd document, which I then source or in some other way recall in both documents, at knitting time. How can I do that?

I heard about bookdown, but my problem is a bit different from writing a book with multiple chapters, and either bookdown is not the right tool, or I don't understand how to use it correctly for this use case. If I just put an index.Rmd file in the same folder as background.Rmd, data_driven_report.rmd and first_principles_based_report.rmd, then once I knit index.Rmd , it tries to knit all three documents together, rather than two separate documents.

I could of course create two different folders with two different index.Rmd documents, one for data_driven_report.rmd and the other for first_principles_based_report.rmd. But I would have to copy background.Rmd to both folders. If I make a modification to the background.Rmd file in one folder, I need to remember to copy it to the other folder. It's not exactly error prone, and a step above my current cut&paste approach, but still not great. Can you help me adopt better knitting practices? Thanks!


I'm happy to report that you can use knitr child documents to do exactly what you want!

Move your section called Background into a new R Markdown document called background.Rmd. Then, in both of your reports you can include the background section using an R chunk like this:

```{r child="background.Rmd"}

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.