r - 渲染 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
修改全局环境。我如何实现这一目标?
解决方案
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())
推荐阅读
- reactjs - 在 React 中用正确的小数计算三角形面积
- mysql - 优化 MySQL Query - 多列搜索条件
- setinterval - Discord.js - 如何每 15 秒更改一次机器人的存在?
- javascript - 点击页面没有加载更多内容
- reactjs - React-App- Rewired 不会添加 Babel 插件
- python - 使用 PIP 安装的 PyAudio 缺少文件?
- javascript - javascript 类 - 具有访问权限的 iife 方法
- javascript - 带标签的父/子复选框
- python - 这两种python导入方法有什么区别?
- ruby-on-rails - 为什么我的电子邮件下载链接会打开一个新的浏览器选项卡?