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 :-)
strange behaviour when sourcing inside function
3 messages · Noia Raindrops, Jannis
Hello,
If argument 'local' is FALSE, 'source' function is evaluating the file in global environment
and object 'a' is not in global environment.
Function's environment is just local. And environment() in a function returns the function's environment.
test <- function () source("test.R", local = FALSE)
# test.R is evaluated in global environment.
test <- function () source("test.R", local = environment())
# environment() returns the envrionment of 'test' function.
test <- function () source("test.R", local = TRUE)
# this is same as above.
Noia Raindrops noia.raindrops at gmail.com
Thanks for your reply! You may be correct, but the documentation of "source" reads as whether the opposite is the case regarding the use of TRUE and FALSE, doesn't it? Your interpretation may be correct (it would be also in line with my inutive interpretation of the combination of the word local and the corresponding boolean values) but if it is, the manual (to me) is misleading. Cheers Jannis
On 22.08.2012 21:25, Noia Raindrops wrote:
Hello,
If argument 'local' is FALSE, 'source' function is evaluating the file in global environment
and object 'a' is not in global environment.
Function's environment is just local. And environment() in a function returns the function's environment.
test <- function () source("test.R", local = FALSE)
# test.R is evaluated in global environment.
test <- function () source("test.R", local = environment())
# environment() returns the envrionment of 'test' function.
test <- function () source("test.R", local = TRUE)
# this is same as above.