Functions called within a function (ie subfunctions) must be defined within that function to access any variables defined in the local environment without being passed.
This fails:
bar <- function() {
z <- x + y
return(z)
}
foo <- function() {
y <- 3
z <- bar()
return(z)
}
foo()
Error in bar() : object 'y' not found
This works:
foo <- function() {
bar <- function() {
z <- x + y
return(z)
}
y <- 3
z <- bar()
return(z)
}
foo()
4