6
votes

I have a master markdown file, e.g., Parent.Rmd, and a number of child documents being included with:

```{r child="introduction.Rmd", echo=FALSE}
```

```{r child="chapter2.Rmd", echo=FALSE}
```

It seems that I should be able to do:

```{r child="Rmd/introduction.Rmd", echo=FALSE}
```

to pull the same file from a sub directory named 'Rmd' but knitr can't open the connection.

I've also tried to use:

`knitr::opts_chunk$set(child.path='Rmd')`

but the chunk code ignores it. Is there another way? My rmarkdown version is 0.9.5 and knitr is 1.12

1
Thanks. Related, probably so, but not directly applicable from what I can tell. We chose not to use LaTeX...Alan
I tried to reproduce the issue with knit 1.12.3 and cannot reproduce it. This document works just fine with first.Rmd and second.Rmd in the subfolder rmd.CL.

1 Answers

0
votes

hopefully, @Yihui will be able to answer your question more elegantly than my proposed solution here. :)

i did a hack earlier here Include HTML files in R Markdown file?. And the method should work for your requirements as well

bookstruct.Rmd file:

---
title: "BookTitle"
output: html_document
---

My introduction goes here

<<insertHTML:[chapters/chapter2.Rmd]

some practice questions

<<insertHTML:[chapters/chapter3.Rmd]

chapters/chapter2.Rmd file:

## Chapter 2

This is my chapter 2.

chapters/chapter3.Rmd file:

## Chapter 3

This is my chapter 3.

In R console, run this:

library(stringi)

subRender <- function(mdfile, flist) {
    #replace <<insertHTML:flist with actual html code
    #but without beginning white space
    rmdlines <- readLines(mdfile)
    toSubcode <- paste0("<<insertHTML:[",flist,"]")
    locations <- sapply(toSubcode, function(xs) which(stri_detect_fixed(rmdlines, xs)))
    subfiles <- lapply(flist, function(f) stri_trim(readLines(f)))
    strlens <- sapply(subfiles,length)

    #render html doc
    newRmdfile <- tempfile("temp", getwd(), ".Rmd")

    #insert flist at specified locations
    #idea from @Marek in [2]
    alllines <- c(rmdlines[-locations], unlist(subfiles))
    ind <- c( (1:length(rmdlines))[-locations],
        unlist(lapply(1:length(locations), function(n) locations[n] + seq(0, 1, len=strlens[n])/1.1 )) )
    sortedlines <- alllines[order(ind)]

    #render html
    write(sortedlines, newRmdfile)
    rmarkdown::render(newRmdfile, "html_document")
    shell(gsub(".Rmd",".html",basename(newRmdfile),fixed=T))
} #end subRender

subRender(mdfile="bookstruct.Rmd",
    flist=list("chapters/chapter2.Rmd", "chapters/chapter3.Rmd"))

[2] How to insert elements into a vector?