从函数内部将函数环境设置为调用环境(parent.frame)的环境

编程入门 行业动态 更新时间:2024-10-24 17:30:36
本文介绍了从函数内部将函数环境设置为调用环境(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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-19 12:07:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/645272.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:环境   函数   部将   设置为   frame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!