【问题标题】:Is there a way to include child Rmd files from a different directory有没有办法包含来自不同目录的子 Rmd 文件
【发布时间】:2016-08-02 04:20:00
【问题描述】:

我有一个主 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

【问题讨论】:

  • 谢谢。相关,可能是这样,但据我所知并不直接适用。我们选择不使用 LaTeX...
  • 我尝试用 knit 1.12.3 重现该问题,但无法重现。 This 文档与子文件夹 rmd 中的 first.Rmdsecond.Rmd 一起工作得很好。

标签: r include knitr r-markdown


【解决方案1】:

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

我早些时候在这里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]

章节/chapter2.Rmd 文件:

## Chapter 2

This is my chapter 2.

章节/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]How to insert elements into a vector?

【讨论】:

  • @chinsoo12:感谢您的努力。在尝试您的解决方案之前,我将尝试将所有 Rmd 放在一个目录中,并在源渲染处更改到该目录。如果这不起作用,那么我将尝试应用您的解决方案。我的问题背后是整理我们的主要项目目录。再次感谢。
  • 同一个目录的想法似乎可行;见stackoverflow.com/questions/25824795/…
猜你喜欢
  • 1970-01-01
  • 2016-05-23
  • 2013-09-11
  • 1970-01-01
  • 2011-02-02
  • 2022-07-17
  • 1970-01-01
  • 2012-02-18
相关资源
最近更新 更多