Reputation: 11371
There are plenty of examples about updating global variables from the inside of R functions by using <<-
or assign()
(here is just one example), but I can't find any examples on how to use such variables as input for functions. For instance, consider this MATLAB function, which is just a complicated way of adding pi to a number:
function final = parentFun(why)
global pie
pie = pi;
final = childFun(why);
end
function y = childFun(x)
global pie
y = x + pie;
end
So that
>> parentFun(100)
ans =
103.1416
I would like to recreate this in R. The closest I got was by nesting childFun
into parentFun
like this:
parentFun <- function(why) {
pie <- pi
childFun <- function(x) {
x + pie
}
childFun(why)
}
And indeed
> parentFun(100)
[1] 103.1416
The problem is that in my real case parentFun
is a couple hundred lines long and it contains several children which can be just as long. In other words, nesting is basically off the table.
Also, these are functions in a package, so pie
is in fact acquired from within a function and isn't started by a script.
Of course, separating both functions doesn't work because childFun()
can't see pie
:
> parentFun <- function(why) {
pie <- pi
childFun(why)
}
> childFun <- function(x) {
x + pie
}
> parentFun(100)
Error in x + pie : non-numeric argument to binary operator
Upvotes: 1
Views: 55
Reputation: 11981
One possibility would be to change the environment of childfun
childFun <- function(x) {
x + pie
}
parentFun <- function(why) {
pie <- pi
environment(childFun) <- environment()
childFun(why)
}
parentFun(100)
[1] 103.1416
This has to do with lexical scoping of R. When you call a function R looks for the variables inside the function environment first. If it is not sucessful R continues the search in parent environments (in your case the global environment).
By writing environment(childFun) <- environment()
you tell the function to look in the environment of parentFun
for variables.
I recommend this book if you want to learn more about environments.
Upvotes: 3