作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
(关于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/
我是一名优秀的程序员,十分优秀!