Embed text files written with markdown syntax in another RMarkdown file

Viewed 889

I know this seems to be a question already answered in StackOverflow.

However, I am going to try to explain my situation clearly.

  1. I am writing 3 separate documents using RStudio and RMarkdown. In fact, I am not including any chunks, so it might be purely Markdown syntax.
  2. These three documents (.Rmd) share some sections, which are identical in the three of them.
  3. There are other sections that are different among them.

In order to write efficiently, I would like to write the common sections using Markdown syntax in separate files from the three documents I mentioned.

In this way, I would like to include and link those common sections in the three documents (in their respective places).

In this regard, I would like knitr, when converting to HTML PDF or DOCX, to take into consideration the syntax of the separate and common sections. I mean, if there are subheadings, bold, italics, etc, to be correctly identified and converted.

Any idea on how to do this?

1 Answers

There are various ways to do this. Here the first two that came to my mind:

Using readLines:

This is basically the approach from the question you linked to, but you have to add the chunk option results="asis":

```{r results="asis"}
cat(readLines('somefile.txt'), sep = '\n')
```

Using read_chunk:

You can also read multiple code chunks from an external script and then use the asis engine to display the chunks you refer to with ref.label:

Your RMD file:

```{r}
knitr::read_chunk("mychunks.R")
```

```{asis, ref.label="firstchunk"}
```

```{asis, ref.label="secondchunk"}
```

File mychunks.R:

## ---- firstchunk

Text

# Header

Text

## ---- secondchunk

Text2

# Header2

Text2
Related