How to insert text from files into RMarkdown documents

Is there a command to insert text from a file into an .Rmd document, so that it appears as if the text in the file had been copied and pasted into the document?
Similar to what source() does for code, but for text with formatting.

The aim is either to insert standard boiler-plate text for documents and make sure that all documents are regenerated consistently if it changes, or to change the language of a document by parameterising the file names of the text sections.


What kind of file/text do you want to inject into the Rmd file? Is it plain-text only, or does it also need to be properly rendered?

It would be plain text, but with formatting commands such as HTML tags or LaTeX commands.
It wouldn't be rendered independently of the Rmd document into which it is inserted.

I should say, I am just evaluating R and RStudio to see if it is something we should migrate to.
Currently I am just speculating about potential applications rather than having a real live problem to solve, but this sort of automated or parameterised report generation would make it very interesting.

Oh okay, well the short answer is yes, you can definitely insert arbitrary amounts of plain-text into R Markdown files. These plain-text files can contain HTML or LaTeX depending on the output format. You can also include external Rmd files which will be inserted into the main Rmd file and rendered. Lots of good ways to do things. The only limit is your time and imagination!

There is one other limit - my complete ignorance of how to actually do this!

Is there a particular syntax or function you can suggest?

I just found this

{r test, child="Test.Rmd", eval=TRUE}

which seems to include the text and chunks from Test.Rmd quite nicely.

I also found that I can't type 3 quotes on this forum :smile:

Now I can go back to being limited by my time and imagination.


Yes, child documents were the way I was going to recommend. The child Rmd file can include prose only (including HTML or LaTeX), or it can include R code that needs to be executed and rendered. Quite flexible.

Quite flexible indeed. It would presumably also make it possible to build document sections separately, render them separately for checking and then bolt them together at the end. I am surprised it isn't emphasised more widely.

I believe child Rmd documents are merged into the main document before knitting/rendering (edit: actually I am not completely sure this is true). So you aren't actually rendering them separately. You can do separate knitting and then combine them at the end using bookdown.

There are two rendering approaches when you are trying to combine multiple Rmd files into a single master document: knit and merge or merge and knit. Both have merits. See here for a more complete description.

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