[英]Using purl to source a .Rmd file from within a Rnw file
我在 .Rmd 文件中做了一些分析。 我现在想在我正在编写为 .Rnw 文件的报告中使用在此文件中创建的一些对象。 由于从 Sweave 切换到 knittr 作为编织引擎,会发生以下情况:
如果我在控制台中运行purl(input = 'myfile.Rmd', output = 'myfile.R')
行,我会得到一个 .R 文件,该文件仅包含来自 05731237D6EE04 块的 ZE1E1D3D405731237D6EE0 这就是我想要的。 但是,如果我将此行放入 .Rnw 文件并编织它(即 .Rnw 文件),我最终会得到一个myfile.R
并且没有错误,但它完全是空的(由于某种原因,除了一个换行符)。
我还尝试将knitr::opts_chunk$set(purl = TRUE)
和knit_hooks$set(purl = hook_purl)
放在 .Rmd 文件中,然后在 my.Rnw 文件中使用knit()
而不是 purl purl()
,但是结果是一样的。
下面是一个小例子:
测试.Rnw
\documentclass{article}
\begin{document}
<<test>>=
library(knitr)
purl(input = 'test.Rmd', output = 'test.R')
@
\end{document}
测试.Rmd
```{r}
answer <- 42
```
预期 Output:
## ------------------------------------------------------------------------
answer <- 42
实际 output:
这个事情谁有经验? 这是一个错误还是我错过了什么? 谢谢您的帮助!
根据?purl
:
knitr将尝试根据输入文档的文件扩展名决定模式列表,例如
Rnw
文件使用列表apat$rnw
,tex
使用列表apat$tex
,brew
使用apat$brew
和 HTML 文件使用apat$html
但显然,这并不是故事的全部。 请注意, purl
本质上只是knit
的包装。 我的猜想是,在编织 RNW 文档时,有一些全局选项集使knit
只查找类似purl
的模式,即使您从 RNW 文档中获取 RMD 文件也是如此。
要解决此问题,请通过在pat_md()
purl()
式设置 Markdown 模式。 之后,恢复以前的模式,以免干扰 RNW 文档的其余部分。
\documentclass{article}
\begin{document}
<<test>>=
library(knitr)
opat <- knit_patterns$get()
pat_md()
purl(input = 'test.Rmd', output = 'test.R')
knit_patterns$set(opat)
@
\end{document}
@Cl. 的猜想是正确的。 function knitr::knit()
引入了很多副作用,包括设置解析模式。 在这种情况下,我强烈建议您在单独的 R session 中运行 purl purl()
。 一种方法是改变
purl(input = 'test.Rmd', output = 'test.R')
至
xfun::Rscript_call(purl, list(input = 'test.Rmd', output = 'test.R'))
This makes sure purl()
is called in a new R session that is (pretty much) independent of the current R session, so the parsing patterns set in the current R session will not affect the new R session's knitr::knit()
call .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.