bez*_*out 1 nested r function function-declaration
(关于R语言)
我试图在另一个函数中声明/定义一个函数。它似乎不起作用。我不认为这完全是一个错误,它可能是预期的行为,但我想了解为什么!任何链接到相关手册页的答案也非常受欢迎。
谢谢
代码 :
fun1 <- function(){
print("hello")
fun2 <- function(){ #will hopefully define fun2 when fun1 is called
print(" world")
}
}
fun1() #so I expected fun2 to be defined after running this line
fun2() #aaand... turns out it isn't
Run Code Online (Sandbox Code Playgroud)
执行 :
> fun1 <- function(){
+ print("hello")
+ fun2 <- function(){ #will hopefully define fun2 when fun1 is called
+ print(" world")
+ }
+ }
>
> fun1() #so I expected fun2 to be defined after running this line
[1] "hello"
> fun2() #aaand... turns out it isn't
Error : could not find function "fun2"
Run Code Online (Sandbox Code Playgroud)
小智 5
如果 'fun1' 返回您分配给 'fun2' 的函数的另一种方法:
> fun1 <- function(){
+ print("hello")
+ # return a function
+ function(){ # function to be returned
+ print(" world")
+ }
+ }
> fun2 <- fun1() # assign returned function to 'fun2'
[1] "hello"
> fun2()
[1] " world"
Run Code Online (Sandbox Code Playgroud)