Insert Portions of a Markdown Document Inside Another Markdown Document Using Knitr

insert portions of a markdown document inside another markdown document using knitr

  1. that is what the chunk option child is for, e.g. in second.Rmd, you can

    ```{r child='first.Rmd'}
    ```
  2. that is a little bit trickier, but you can call knit_child() manually, e.g.

    ```{r echo=FALSE, results='asis'}
    # knit the first three lines of first.Rmd
    cat(knit_child(text = readLines('first.Rmd')[1:3]), sep = '\n')
    ```

How to link to part of the same document in Markdown?

In pandoc, if you use the option --toc in producing html, a table of contents will be produced with links to the sections, and back to the table of contents from the section headings. It is similar with the other formats pandoc writes, like LaTeX, rtf, rst, etc. So with the command

pandoc --toc happiness.txt -o happiness.html

this bit of markdown:

% True Happiness

Introduction
------------

Many have posed the question of true happiness. In this blog post we propose to
solve it.

First Attempts
--------------

The earliest attempts at attaining true happiness of course aimed at pleasure.
Soon, though, the downside of pleasure was revealed.

will yield this as the body of the html:

<h1 class="title">
True Happiness
</h1>
<div id="TOC">
<ul>
<li>
<a href="#introduction">Introduction</a>
</li>
<li>
<a href="#first-attempts">First Attempts</a>
</li>
</ul>
</div>
<div id="introduction">
<h2>
<a href="#TOC">Introduction</a>
</h2>
<p>
Many have posed the question of true happiness. In this blog post we propose to solve it.
</p>
</div>
<div id="first-attempts">
<h2>
<a href="#TOC">First Attempts</a>
</h2>
<p>
The earliest attempts at attaining true happiness of course aimed at pleasure. Soon, though, the downside of pleasure was revealed.
</p>
</div>

Include a specific chunk from one markdown document in another document

I would try purl-ing the original child document and then reading the chunk in from the code tangle file, which you can then subsequently delete.

Here's test-main.Rmd

```{r echo=FALSE}
invisible(purl("test-child.Rmd", output="temp", quiet=TRUE))
read_chunk("temp")
```

```{r ref.label='test_child_2'}
```

```{r echo=FALSE}
unlink("temp")
```

I modified your test-child.Rmd to use different labels because yours weren't working on my machine:

Hi, there. I'm a child.

```{r test_child_1}
1+1
dnorm(0)
```

```{r test_child_2}
2+2
dnorm(0)
```

The output of knit('test-main.Rmd') is thus:

```r
2+2
```

```
## [1] 4
```

```r
dnorm(0)
```

```
## [1] 0.3989
```

Embed text files written with markdown syntax in another RMarkdown file

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

How to combine two RMarkdown (.Rmd) files into a single output?

August, 2018 update: This answer was written before the advent of bookdown, which is a more powerful approach to writing Rmarkdown based books. Check out the minimal bookdown example in @Mikey-Harper's answer!

When I want to break a large report into separate Rmd, I usually create a parent Rmd and include the chapters as children. This approach is easy for new users to understand, and if you include a table of contents (toc), it is easy to navigate between chapters.

report.Rmd

---  
title: My Report
output:
pdf_document:
toc: yes
---

```{r child = 'chapter1.Rmd'}
```

```{r child = 'chapter2.Rmd'}
```

chapter1.Rmd

# Chapter 1

This is chapter 1.

```{r}
1
```

chapter2.Rmd

# Chapter 2

This is chapter 2.

```{r}
2
```

Build

rmarkdown::render('report.Rmd')

Which produces:
My report

And if you want a quick way to create the chunks for your child documents:

rmd <- list.files(pattern = '*.Rmd', recursive = T)
chunks <- paste0("```{r child = '", rmd, "'}\n```\n")
cat(chunks, sep = '\n')
# ```{r child = 'chapter1.Rmd'}
# ```
#
# ```{r child = 'chapter2.Rmd'}
# ```

Preserve markdown in chunked file for knitr

If you import Rmd into Rmd files, you can use one of the solutions described here: either using the chunk parameter child

```{r, child = 'pathtofile/actualAnalysis.R'}
```

or using the function knit_child (which returns the converted document as a string) together with the chunk parameter results set to 'asis':

```{r echo=FALSE, results='asis'}
cat(knit_child(text = readLines('pathtofile/actualAnalysis.Rmd', quiet = TRUE))
```

If the imported files are formatted R scripts to be processed with spin, the same should work after replacing knit_child by spin_child.

If the parent document itself was also such a formatted R script to be processed with spin (not an Rmd, as in your example), you could import child documents (formatted for spin) using double curly braces, as described in the spin_child documentation:

{{ spin_child('pathtofile/actualAnalysis.R') }}

Source code from Rmd file within another Rmd

After some further searching, I've found a solution. There is a package option in knitr that can be set to change the behavior for handling duplicate chunks, appending a number after their label rather than failing with an error. See https://github.com/yihui/knitr/issues/957.

To set this option, use options(knitr.duplicate.label = 'allow').

For the sake of completeness, the full code for the function I've written is

source_rmd <- function(file, local = FALSE, ...){
options(knitr.duplicate.label = 'allow')

tempR <- tempfile(tmpdir = ".", fileext = ".R")
on.exit(unlink(tempR))
knitr::purl(file, output=tempR, quiet = TRUE)

envir <- globalenv()
source(tempR, local = envir, ...)
}

Conditionally display block of markdown text using knitr

You could use the asis engine to conditionally include/exclude arbitrary text in knitr, e.g.

```{asis, echo=FALSE}
Some arbitrary text.

1. item
2. item

Change echo=TRUE or FALSE to display/hide this chunk.
```

But I just discovered a bug in this engine and fixed it. Unless you use knitr >= 1.11.6, you can create a simple asis engine by yourself, e.g.

```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) paste(options$code, collapse = '\n')
})
```

If you want to include inline R expressions in the text, you will have to knit the text, e.g.

```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
```

Use multiple R Markdown files in Shiny tabs

As an alternative to the approach mentioned in earlier answer you may want to try the approach illustrated in this repo https://github.com/vnijs/shiny-site. This is a proof of concept that you can render rmarkdown files using Knitr within a shiny without app having to break up the file into parts. It works by using Shiny's renderUI functionality and evaluating the rmarkdown file in the shinyServer environment.



Related Topics



Leave a reply



Submit