bezout
bezout

Reputation: 143

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"

Upvotes: 2

Views: 2973

Answers (2)

Retired Data Munger
Retired Data Munger

Reputation: 1445

another way if for 'fun1' to return a function that you assign to '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"

Upvotes: 6

mts
mts

Reputation: 2190

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"

Upvotes: 3

Related Questions