I have created two functions below that are both defined in the global environment. You'll notice that foo()
is called within bar()
and they share the one input which is x
. :
bar <- function() {
x <- 2
foo()
}
foo <- function(x) {
x * 1000
}
x
is not explicitly defined when foo()
is called within bar()
, which is causing an error with the following code:
bar()
My question is this: is there a way to define the environment where foo()
tries to find x
? From my research, foo()
is looking for x
in the global environment, but ideally it should be taking x
from the environment of bar()
, where x <- 2
.
I know that the following would fix the problem, but this isn't a reasonable option in the code I'm developing. The key is getting foo()
to reference the x
value from the environment of bar()
:
bar <- function() {
x <- 2
foo(x = x)
}
foo <- function(x) {
x * 1000
}
bar()