I read about scoping in 'Advanced R' and still didn't figure this out.
I defined two functions.
in file 'f1.R'
:
f1 = function(x, y) {
x = x + 1
y = y + 1
z = 1
fsum(x, y)
}
in file 'fsum.R'
:
fsum = function(x, y){
x + y + z
}
Now it doesn't work because fsum
can't find z
, due to scope issue
> source('f1.R')
> source('fsum.R')
> f1(1,1)
Error in fsum(x, y) : object 'z' not found
> environment(f1)
<environment: R_GlobalEnv>
> environment(fsum)
<environment: R_GlobalEnv>
How can I make fsum to look up for needed variables in local environment? I did some test, and
Solution 1: explicitly pass the variable as argument
in file 'f1.R'
:
f1 = function(x, y) {
x = x + 1
y = y + 1
z = 1
fsum(x, y, z)
}
in file 'fsum.R'
:
fsum = function(x, y, z){
x + y + z
}
Now it works:
> source('f1.R')
> source('fsum.R')
> f1(1,1)
[1] 5
But what if there are lots of variables needed in fsum
and I don't want to explicitly write them down? Thanks for help. Any recommendation of readings is appreciated.
PS: I read something about making variables global using <<
. This is not what I'm looking for. I'd like variables to be local.
Solution 2: If a function is defined in another function, then its environment is the local, and it can access the variables.
In this case I don't want to define fsum
inside f1
anyway because I want to use fsum
anywhere)
in file 'f1.R'
:
f1 = function(x, y) {
x = x + 1
y = y + 1
z = 1
source('fsum.R', local=T)
fsum(x, y)
}
in file 'fsum.R'
:
fsum = function(x, y){
x + y + z
}
And it works:
> source('f1.R')
> f1(1,1)
[1] 5