有没有一种方法可以从不同目录中包含子Rmd文件?

6

我有一个主要的 markdown 文件,例如 Parent.Rmd,以及一些被包含在其中的子文档:

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

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

我应该能够做到以下事情:

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

从名为“Rmd”的子目录中提取相同的文件,但knitr无法打开连接。
我也尝试使用:
`knitr::opts_chunk$set(child.path='Rmd')`

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


请问这与编程有关吗?https://dev59.com/n4Tba4cB1Zd3GeqP6XfL - baptiste
谢谢。相关,但据我所知并不直接适用。我们选择不使用LaTeX... - Alan
我尝试使用knit 1.12.3重现问题,但无法重现。这个文档在子文件夹rmd中使用first.Rmdsecond.Rmd完全正常。 - CL.
1个回答

0
希望@Yihui能够比我提出的解决方案更优雅地回答你的问题。 :)
我之前在这里进行了一次hack 如何在R Markdown文件中包含HTML文件?。这种方法也适用于您的要求。
bookstruct.Rmd文件:
---
title: "BookTitle"
output: html_document
---

My introduction goes here

<<insertHTML:[chapters/chapter2.Rmd]

some practice questions

<<insertHTML:[chapters/chapter3.Rmd]

chapters/chapter2.Rmd 文件:

## Chapter 2

This is my chapter 2.

chapters/chapter3.Rmd 文件:

## Chapter 3

This is my chapter 3.

在 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"))

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


@chinsoo12:感谢你的努力。在尝试你的解决方案之前,我将尝试将所有的Rmd文件放在一个单独的目录中,并在源渲染时切换到该目录。如果这不起作用,那么我将尝试应用你的解决方案。我的问题背后是为了使我们的主项目目录更加清晰。再次感谢。 - Alan
相同的目录想法似乎可行;请参见 https://dev59.com/j18e5IYBdhLWcg3wYJYN - jsta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接