I'd like to feed a value from one function into another that I'm calling on inside the first, and I can't seem to get the scoping right. Crucially, the two functions are defined separately. Here's an example:
little_fun <- function(){
print(paste("CheckNumber exists in parent frame =", exists("CheckNumber", where = parent.frame())))
print(paste("CheckNumber exists in current frame =", exists("CheckNumber")))
if(exists("CheckNumber", where = parent.frame())){
print(CheckNumber + 2)
}
}
Running little_fun()
by itself returns
[1] "CheckNumber exists in parent frame = FALSE"
[1] "CheckNumber exists in current frame = FALSE"
which is what I expected. However, I want to make a more complicated function that calls on little_fun internally.
big_fun <- function(y){
CheckNumber <- 5
little_fun()
}
Calling on big_fun returns this:
[1] "CheckNumber exists in parent frame = TRUE"
[1] "CheckNumber exists in current frame = FALSE"
Error in print(CheckNumber + 2) : object 'CheckNumber' not found
It makes sense to me that CheckNumber exists in the parent frame but not in the current frame. But how can CheckNumber exist in the parent frame but not be available for adding to 2? I thought that R would keep climbing the environment tree until it found the variable it needed. What's going on here?