gpt4 book ai didi

R : define a function within a function

转载 作者:行者123 更新时间:2023-12-05 08:57:29 25 4
gpt4 key购买 nike

(关于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"

最佳答案

如果“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"

关于R : define a function within a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31472339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com