I have an R code which looks like:
我有一个R代码,看起来像:
func1 = function(a) {
func2 = function(a) {
return(a+2)
}
func3 = function(a) {
return(a+3)
}
return(a+func2(a))
}
Is it possible that I be able to call func2 or func3 from outside func1? eg. How do I run:
我是否有可能从func1外部调用func2或func3?例如。我该怎么办:
x <- func2(10) #from the console?
2 个解决方案
#1
1
You could create a function closure:
你可以创建一个函数闭包:
##I've removed the brackets and return to shorten the function
func1 = function(a) {
func2 = function(a) a+2
func3 = function(a) a+3
return(list(func2=func2, func3=func3))
}
You can use the closure to share variables:
您可以使用闭包来共享变量:
func1 = function(a) {
a = a
func2 = function() a + 2
func3 = function() a + 3
return(list(func2=func2, func3=func3))
}
f = func1(50)
f$func2()
f$func3()
#2
0
No You can't.
不,你不能。
func2 is defined in the scope of func1.
func2在func1的范围内定义。
But The question is really ambiguous ! Any netsed function has access to the global scope.
但这个问题真的很模糊!任何netsed函数都可以访问全局范围。
a <- 10
function <- f(x){
g <- function(y=x) x+a
g(x)
}
here function g is nested and has a free variable a. the interpreter lokks in the scope of g and f and next looks for a value for a in the local frame of f(the global)
这里函数g是嵌套的并且有一个*变量a。解释器在g和f的范围内lokks,然后在f的本地帧中寻找a的值(全局)
Why defining a nested function as nested if you want access to it as global?
如果要将嵌套函数作为全局访问,为什么要将嵌套函数定义为嵌套函数?
#1
1
You could create a function closure:
你可以创建一个函数闭包:
##I've removed the brackets and return to shorten the function
func1 = function(a) {
func2 = function(a) a+2
func3 = function(a) a+3
return(list(func2=func2, func3=func3))
}
You can use the closure to share variables:
您可以使用闭包来共享变量:
func1 = function(a) {
a = a
func2 = function() a + 2
func3 = function() a + 3
return(list(func2=func2, func3=func3))
}
f = func1(50)
f$func2()
f$func3()
#2
0
No You can't.
不,你不能。
func2 is defined in the scope of func1.
func2在func1的范围内定义。
But The question is really ambiguous ! Any netsed function has access to the global scope.
但这个问题真的很模糊!任何netsed函数都可以访问全局范围。
a <- 10
function <- f(x){
g <- function(y=x) x+a
g(x)
}
here function g is nested and has a free variable a. the interpreter lokks in the scope of g and f and next looks for a value for a in the local frame of f(the global)
这里函数g是嵌套的并且有一个*变量a。解释器在g和f的范围内lokks,然后在f的本地帧中寻找a的值(全局)
Why defining a nested function as nested if you want access to it as global?
如果要将嵌套函数作为全局访问,为什么要将嵌套函数定义为嵌套函数?