有没有办法包含来自其他目录的子Rmd文件 [英] Is there a way to include child Rmd files from a different directory
问题描述
我有一个主要的降价文件,例如Parent.Rmd,以及随附的许多子文档:
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}
```
看来我应该能够做到:
```{r child="Rmd/introduction.Rmd", echo=FALSE}
```
从名为"Rmd"的子目录中提取相同的文件,但knitr无法打开连接.
to pull the same file from a sub directory named 'Rmd' but knitr can't open the connection.
我也尝试使用:
`knitr::opts_chunk$set(child.path='Rmd')`
,但块代码将忽略它.还有另一种方法吗?我的rmarkdown版本是0.9.5,knitr是1.12
but the chunk code ignores it. Is there another way? My rmarkdown version is 0.9.5 and knitr is 1.12
推荐答案
希望,@Yihui可以比我在这里提出的解决方案更优雅地回答您的问题. :)
hopefully, @Yihui will be able to answer your question more elegantly than my proposed solution here. :)
我早些时候在这里进行过黑客攻击在R中包含HTML文件降价文件?.而且该方法也可以满足您的要求
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文件:
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文件:
chapters/chapter2.Rmd file:
## Chapter 2
This is my chapter 2.
chapters/chapter3.Rmd文件:
chapters/chapter3.Rmd file:
## Chapter 3
This is my chapter 3.
在R控制台中,运行以下命令:
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] 如何将元素插入向量?
这篇关于有没有办法包含来自其他目录的子Rmd文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!