将函数环境设置为函数内部的调用环境(parent.frame) [英] Set a functions environment to that of the calling environment (parent.frame) from within function

查看:234
本文介绍了将函数环境设置为函数内部的调用环境(parent.frame)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然在努力与R的范围和环境。我想要构建简单的帮助函数,从我的'main'函数调用,可以直接引用这些主要函数中的所有变量 - 但是我不想在每个主要的函数中定义帮助函数功能。

  helpFunction< -function(){
#can我可以添加一行来改变这个帮助函数的环境到调用函数的那个​​?
return(importantVar1 + 1)
}

mainFunction< function(importantVar1){
return(helpFunction())
}

mainFunction(importantVar1 = 3)#so这应该输出4


解决方案

嗯,一个函数不能改变它的默认环境,但你可以使用 eval 在不同的环境中运行代码。我不知道这完全符合优雅,但这应该是有效的:

  helpFunction< -function(){
eval(quote(importantVar1 + 1),parent.frame())
}

mainFunction< function(importantVar1){
return(helpFunction())
}

mainFunction(importantVar1 = 3)


I am still struggling with R scoping and environments. I would like to be able to construct simple helper functions that get called from my 'main' functions that can directly reference all the variables within those main functions - but I don't want to have to define the helper functions within each of my main functions.

helpFunction<-function(){
#can I add a line here to alter the environment of this helper function to that of the calling function?
return(importantVar1+1)
}

mainFunction<-function(importantVar1){
return(helpFunction())
}

mainFunction(importantVar1=3) #so this should output 4

解决方案

Well, a function cannot change it's default environment, but you can use eval to run code in a different environment. I'm not sure this exactly qualifies as elegant, but this should work:

helpFunction<-function(){
    eval(quote(importantVar1+1), parent.frame())
}

mainFunction<-function(importantVar1){
    return(helpFunction())
}

mainFunction(importantVar1=3)

这篇关于将函数环境设置为函数内部的调用环境(parent.frame)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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