How can I make x available in f2()?
f1 <- function(){
x <- 5
f2()
}
f2 <- function(){
x
}
f1()
#> Error in f2() : object 'x' not found
On
The general answer to this question is:
By explicitly passing x to f2() via a function argument:
f1 <- function () {
x <- 5
f2(x)
}
f2 <- function (x) {
x
}
f1()
# [1] 5
Argument passing is an incredibly common pattern in programming, and is the correct answer 99% of the time when you need to make values available inside a function. Do not be tempted to avoid passing arguments into functions merely “for convenience”.
There are very specific scenarios in which R’s non-standard evaluation features (show-cased in the other answer) are an appropriate solution. But “for convenience” isn’t a valid reason, because it makes the code harder to understand, reuse and error-check.
As mentioned in the comments one normally passes objects via the arguments from one function to another but if for some reason that is not desirable in this case then here are some options.
1) Define f2 within f1.
2) or create a local copy of f2 and reset its environment to the execution environment of f1. The first line of f1 below does both. This modifies the source of f1 but not f2
3) macro Turn f2 into a macro. This modifies the source of f2 but not f1. This conceptually injects the body of f2 into f1 when f2 is run.
4) defmacro The gtools package has defmacro which essentially does the same thing as (3).