有没有办法包含来自不同目录的子 Rmd 文件

Ala*_*lan 6 r include knitr r-markdown

我有一个主降价文件,例如 Parent.Rmd,以及一些包含在以下文件中的子文档:

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

```{r child="chapter2.Rmd", echo=FALSE}
```
Run Code Online (Sandbox Code Playgroud)

看来我应该能够做到:

```{r child="Rmd/introduction.Rmd", echo=FALSE}
```
Run Code Online (Sandbox Code Playgroud)

从名为“Rmd”的子目录中提取相同的文件,但 knitr 无法打开连接。

我也尝试使用:

`knitr::opts_chunk$set(child.path='Rmd')`
Run Code Online (Sandbox Code Playgroud)

但是块代码忽略了它。还有其他方法吗?我的 rmarkdown 版本是 0.9.5,knitr 是 1.12

chi*_*n12 0

希望@Yihui 能够比我在这里提出的解决方案更优雅地回答你的问题。:)

我之前在这里做了一个 hack Include HTML files in R Markdown file? 。该方法也应该适合您的要求

bookstruct.Rmd 文件:

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

My introduction goes here

<<insertHTML:[chapters/chapter2.Rmd]

some practice questions

<<insertHTML:[chapters/chapter3.Rmd]
Run Code Online (Sandbox Code Playgroud)

Chapters/chapter2.Rmd 文件:

## Chapter 2

This is my chapter 2.
Run Code Online (Sandbox Code Playgroud)

Chapters/chapter3.Rmd 文件:

## Chapter 3

This is my chapter 3.
Run Code Online (Sandbox Code Playgroud)

在 R 控制台中,运行以下命令:

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"))
Run Code Online (Sandbox Code Playgroud)

[2]如何向向量中插入元素?