在R中编写函数的常规方法(据我所知)是为了避免副作用并从函数返回一个值.
contained <- function(x) {
x_squared <- x^2
return(x_squared)
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,返回从函数输入计算的值.但是变量x_squared不可用.
但是如果你需要违反这个基本的函数式编程原则(我不确定R对这个问题有多严重)并从函数中返回一个对象,你有两个选择.
escape <- function(x){
x_squared <<- x^2
assign("x_times_x", x*x, envir = .GlobalEnv)
}
Run Code Online (Sandbox Code Playgroud)
这两个对象x_squared,并x_times_x返回.一种方法比另一种方法更好,为什么呢?
我仍然在努力寻找R范围和环境.我希望能够构造简单的辅助函数,这些函数可以从我的'main'函数中调用,这些函数可以直接引用这些主函数中的所有变量 - 但是我不想在每个main函数中定义辅助函数功能.
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
Run Code Online (Sandbox Code Playgroud)