The problem is that both alpha and beta are declared inside the Global Environment.
Every function looks for unknown objects into the parent environment.
beta's parent environment is the global environment, so when x is called beta will look for x in the Global Environment: it can't "see" what was created inside alpha's environment.
It would work as you expect:
- if you declare
beta inside alpha environment:
alpha <- function(a) {
beta <- function(b) {
foo <- b + x
print(foo)
}
x <- a + 5
print(x)
beta(2)
}
alpha(1)
#> [1] 6
#> [1] 8
- or if you tell
beta in which environment it should look for x:
beta <- function(b, env = parent.frame()) {
x <- get("x", envir = env)
foo <- b + x
print(foo)
}
alpha <- function(a) {
x <- a + 5
print(x)
beta(2) # by default beta takes alpha's environment as parent frame!
}
alpha(1)
#> [1] 6
#> [1] 8
There are also other options, like assigning x to the alpha's parent environment, but I wouldn't do that.
beta <- function(b) {
foo <- b + x
print(foo)
}
alpha <- function(a) {
x <<- a + 5
print(x)
beta(2)
}
alpha(1)
#> [1] 6
#> [1] 8
I would suggest you to have a look at this.