R:定义函数内的函数

时间:2015-07-17 09:18:21

标签: r function nested 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

执行:

> 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"

2 个答案:

答案 0 :(得分:4)

另一种方法,如果'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"

答案 1 :(得分:2)

这将按预期工作,但在R中通常被认为是不好的做法:

fun1 <- function(){
  print("hello")
  fun2 <<- function(){ #will hopefully define fun2 when fun1 is called
    print(" world")
  }
}

我在函数定义的第3行中将<-更改为<<-。执行:

> fun1 <- function(){
+     print("hello")
+     fun2 <<- function(){ #will hopefully define fun2 when fun1 is called
+         print(" world")
+     }
+ }
> 
> fun1()
[1] "hello"
> fun2()
[1] " world"
相关问题