如何在Rstudio Markdown中使用全局环境中的对象 [英] How to use objects from global environment in Rstudio Markdown

查看:236
本文介绍了如何在Rstudio Markdown中使用全局环境中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Stack Overflow上也看到了类似的问题,但实际上没有确定性的答案,当然也没有适合我的答案.

I've seen similar questions on Stack Overflow but virtually no conclusive answers, and certainly no answer that worked for me.

在Markdown(Rstudio)脚本中访问和使用位于全局R环境中的对象(回归拟合,数据框,其他对象)的最简单方法是什么.

What is the easiest way to access and use objects (regression fits, data frames, other objects) that are located in the global R environment in the Markdown (Rstudio) script.

鉴于RStudio团队倾向于使事情变得舒适和有效,我感到惊讶的是,没有简单的解决方案.

I find it surprising that there is no easy solution to this, given the tendency of the RStudio team to make things comfortable and effective.

谢谢.

推荐答案

不管是好是坏,这种疏忽是有意的.依靠文档外部创建的对象会降低文档的可复制性-也就是说,如果您的文档需要全局环境中的数据,则不能仅仅给某人(或您自己)两年的文档和数据文件,然后让他们重新创建它本身.

For better or worse, this omission is intentional. Relying on objects created outside the document makes your document less reproducible--that is, if your document needs data in the global environment, you can't just give someone (or yourself in two years) the document and data files and let them recreate it themselves.

因此,为了在后台执行渲染,RStudio实际上创建了一个单独的R会话来渲染文档.该后台R会话无法在RStudio中看到的交互式R会话中看到任何环境.

For this reason, and in order to perform the render in the background, RStudio actually creates a separate R session to render the document. That background R session cannot see any of the environments in the interactive R session you see in RStudio.

解决此问题的最佳方法是采用用于创建全局环境内容的代码并将其移入文档内(如果您不希望它显示在文档中,则可以使用echo = FALSE ).这样可以使您的文档自成体系,并且可复制.

The best way around this problem is to take the code you used to create the contents of your global environment and move it inside your document (you can use echo = FALSE if you don't want it to show up in the document). This makes your document self-contained and reproducible.

如果您不能这样做,则可以采用以下几种方法直接在全局环境中使用数据:

If you can't do that, there are a few approaches you can take to use the data in the global environment directly:

  1. 在R控制台中键入rmarkdown::render("your_doc.Rmd"),而不是使用 Knit HTML 按钮.这将在当前会话中进行编织,而不是在后台会话中进行编织.或者:

  1. Instead of using the Knit HTML button, type rmarkdown::render("your_doc.Rmd") at the R console. This will knit in the current session instead of a background session. Alternatively:

在渲染之前将全局环境保存到.Rdata文件(使用R的 load 在您的文档中.

Save your global environment to an .Rdata file prior to rendering (use R's save function), and load it in your document.

这篇关于如何在Rstudio Markdown中使用全局环境中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆