Search code examples
rfunctionnestedfunction-declaration

R : define a function within a function


(about R language)

I was trying to declare/define a function, within another function. It doesn't seem to work. I don't think this is exactly a bug, it's probably expected behavior, but I would like to understand why ! Any answer linking to relevant manual pages is also very welcome.

Thanks

Code :

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

Execution :

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

Solution

  • This will work as you expect but is generally considered bad practice in R:

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

    where I changed <- to <<- in line 3 of the function definition. Execution:

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