so i came across this problem that is to do with variables existing in different environments and it left me very confused as it does not fit with my understanding of how functions look for various objects.
my toy example is very simple: i have a function foo
taking one argument j
. foo
lives inside a function of an lapply
loop with an argument 'i'. now, i
clearly exists within the lapply
environment (and does not in the global one). when called within the lapply function foo
struggles to find i
and throws and error:
foo <- function(j){
message('foo env: exists(j) ', exists('j'))
message('foo env: exists(i) ', exists('i'))
i
}
env.g <- environment()
invisible(lapply(1, FUN = function(i){
message('global env: exists(i) ', exists('i', envir = env.g))
message('lapply env: exists(i) ', exists('i'))
message(' ')
j <- i + 1
foo(j)
}
))
#global env: exists(i) FALSE
#lapply env: exists(i) TRUE
#foo env: exists(j) TRUE
#foo env: exists(i) FALSE
#Error in foo(j) : object 'i' not found
when, on the other hand, i
exists in the global environment, foo
is okay with that:
i <- 10
foo()
#foo env: exists(j) TRUE
#foo env: exists(i) TRUE
#[1] 10
so my prior understanding was that if a function doesn't see a variable in its own environment it goes to the next one up (lapply
in my first example and global env. in my second one), until it finds it. however, it clearly doesn't go to the outer loop of lapply
in the above... why?