[R] strange behaviour when sourcing inside function

Jannis bt_jannis at yahoo.de
Wed Aug 22 18:05:08 CEST 2012


Dear R community,


I encounter a problem that is counterintuitive to my understanding of 
the documentation of source and the "local" argument of that function. 
With the following code, I would expect the content of "test.R" to be 
evaluated inside the environment of the function "test". This, however, 
does not seem to be the case as the object "a" can not be found. Is this 
intended? Do I miss something? Do I misinterpret the documentation of 
source?


test <- function() {
    a = 2
    source('test.R', local = FALSE)
}

The file "test.R" contains the following:

b = 1 + a


I get this error:

Error in eval.with.vis(expr, envir, enclos) : object 'a' not found

With this code, the function runs as intended:

test <- function() {
    a = 2
    source('test.R', local = environment())
}

With my interpretation of the documentation, both versions should do the 
same ....

Thanks for your help!

Jannis


P.S. There seems to be an small typo in the documentation for the 
'local' argument ("...FALSE to the environment from ???? source is 
called...") in case anybody appreciates my pickyness :-)



More information about the R-help mailing list