首页 > 解决方案 > 渲染 RMarkdown 文档时修改全局环境

问题描述

考虑这个最小的 RMarkdown 示例,保存在文件中test.rmd

```{r}
foo <- "bar"
```

如果您使用 渲染此文件,则将在您的全局环境中找到rmarkdown::render("test.rmd")该对象:foo

> foo
Error: object 'foo' not found
> rmarkdown::render("test.rmd")
[...]
Output created: test.html
> foo
[1] "bar"
> 

同样,如果foo已在全局环境中定义,则会对其进行修改:

> foo <- "baz"
> rmarkdown::render("test.rmd")
[...]
Output created: test.html
> foo
[1] "bar"

到现在为止还挺好。

但是,出于我自己的原因,我想包装另一个函数render(),例如

myrender <- function(f) render(f, output_format="html_document")

现在,当我调用 时myrender("test.rmd")foo变量被导出到父环境,在这种情况下,导出到 中的环境myrender,我不能再从全局环境访问它:

> myrender("test.rmd")
[...]
Output created: test.html
> foo
Error: object 'foo' not found

虽然这是预期的行为,但我仍然希望render修改全局环境。我如何实现这一目标?

标签: rr-markdownknitr

解决方案


Let me prefix this by saying that I believe this is a very bad idea. Rendering should happen in its own scope, and ideally its own R process, precisely to avoid interference (I’d even go further: the fact that this works by default is a correctness flaw in the API).

But you can pass an evaluating environment to rmarkdown::render:

myrender <- function(f) render(f, output_format = "html_document", envir = globalenv())

推荐阅读