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

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

问题描述

我仍在为 R 范围界定和环境而苦苦挣扎.我希望能够构建从我的主"函数中调用的简单辅助函数,这些函数可以直接引用这些主函数中的所有变量——但我不想在我的每个主函数中定义辅助函数职能.

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

推荐答案

嗯,一个函数不能改变它的默认环境,但是你可以使用 eval 在不同的环境中运行代码.我不确定这是否完全符合优雅的条件,但这应该可以:

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天全站免登陆