在R中更改功能/全局环境 [英] Changing the functional/global environment in R

查看:172
本文介绍了在R中更改功能/全局环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将R中的工作环境或工作空间设置为已定义的环境?我想在不经常引用环境的情况下在环境中调用变量.我知道可以使用attach函数以这种方式访问​​变量,但是创建的任何变量都不会放回到附加环境中.目标是使所有功能都在 other 环境中发生.

Is there any way to change the set the working environment or workspace in R to a defined environment? I'd like to call the variables in an environment without constantly referring to the environment. I understand that the attach function can be used to access the variable in this manner, but any variables created don't get placed back in the attached environment. The goal is to have all the functions take place in the other environment.

例如:

original.env <- .GlobalEnv
other.env <- new.env()  
other.env$A <- 12; other.env$B <- 1.5
set.env(other.env)  
C <- A + B          
set.env(original.env)   
other.env$C         
[1] 13.5

这是set.env的步骤,我不知道它是否存在,或者还有其他窍门.

It's the step with set.env which I can't figure out if it exists, or there's some other trick to doing this.

此方法的目标是允许在几个非嵌套环境相同代码在具有相同结构的不同数据集上使用,而无需不断调用带有Environment$前缀的其他环境.在很多情况下变得非常冗长.

The goal of this approach is to allow the same code to be used on different data sets with identical structures in several non-nested environments without constantly calling other environments with the Environment$ prefix, which gets really verbose in many cases.

如果还可以将结果分配回设置的环境(如在全局环境中,则所有内容在任何变量前面都具有隐式的.GlobalEnv$),则可以更轻松地从内部访问和返回多个值一个功能.

If the results can also be assigned back to the set environment (as in the global environment, everything has an implicit .GlobalEnv$ in front of any variable) it would make it way easier to access and return multiple values from inside of a function.

感谢您的帮助.谢谢.

推荐答案

您正在寻找eval/evalq

来自help("evalq")

在指定的环境中评估R表达式.

Evaluate an R expression in a specified environment.

具体来说,evalq注意

evalq形式等效于eval(quote(expr),...). eval在将它的第一个参数传递给评估器之前,先在当前范围内对其进行评估:evalq避免了这一点.

The evalq form is equivalent to eval(quote(expr), ...). eval evaluates its first argument in the current scope before passing it to the evaluator: evalq avoids this.

# Therefore you want something like this
evalq(C <- A + B, envir = other.env)

如果要包装多个表达式,请使用{}例如

If you want to wrap more than one expression use {} eg

evalq({C <-A + B
    d <-  5
       }, envir = other.env)

这篇关于在R中更改功能/全局环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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