R:在函数中定义函数
R : define a function within a function
(关于R语言)
我试图 declare/define 一个函数,在另一个函数中。
它似乎不起作用。我不认为这完全是一个错误,它可能是预期的行为,但我想了解原因!任何链接到相关手册页的答案也非常受欢迎。
谢谢
代码:
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"
这会如您所愿地工作,但在 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"
另一种方法,如果 'fun1' 到 return 您分配给 '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"
(关于R语言)
我试图 declare/define 一个函数,在另一个函数中。 它似乎不起作用。我不认为这完全是一个错误,它可能是预期的行为,但我想了解原因!任何链接到相关手册页的答案也非常受欢迎。
谢谢
代码:
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"
这会如您所愿地工作,但在 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"
另一种方法,如果 'fun1' 到 return 您分配给 '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"