Just to clarify, I'm not saying that R has issues. The problem is probably on my side, but I'm really confused. I have a function (make_a()
) that creates a function a()
. I also have a function that uses this function in its definition (fun_using_a()
):
make_a <- function(x) {
a <- function(y) {
x + y
}
a
}
fun_using_a <- function(x) {
a(x)/2
}
Now, I create another function that uses these two:
my_fun <- function(x) {
a <- make_a(1)
fun_using_a(x)
}
Calling my_fun(10)
gives an error:
my_fun(10)
Error in a(x) : could not find function "a"
However, everything works fine if do essentially the same thing in the global environment:
a <- make_a(1)
fun_using_a(10)
[1] 5.5
What's going on here? Why does my_fun(10)
throw an error? It seems that my understanding of R environments must be a bit off somewhere, but I just can't figure it out. When I call my_fun()
, shouldn't the function a()
be defined in the execution environment after the first line and thus fun_using_a()
should be able to find it there (due to lazy evaluation)?
Any help will be greatly appreciated. Thanks a lot!