[R] Confusion regarding environments invoked by "source" command

Duncan Murdoch murdoch at stats.uwo.ca
Mon Mar 23 23:31:01 CET 2009


On 23/03/2009 6:06 PM, Dennis Fisher wrote:
> Colleagues,
> 
> R version 2.8.1 in OS X
> 
> Within a function (which is already within a function), I am sourcing  
> a file.  The syntax of the command is something like (this is just an  
> example; the actual code is much more complicated):

This code works just as expected, once you make it syntactically 
correct.  I suspect you have something else wrong in the real case. 
Here's my log:

 > BIGFUNCTION<- function()
+ {
+ DATAFRAME<- data.frame(a=1:3,b=4:6)
+ MYFUNCTION(DATAFRAME)
+ }
 >
 > MYFUNCTION<- function(DATAFRAME)
+ {
+ print(ls())
+ exists("DATAFRAME")
+ source("myfile.R", local=T)
+ }
 > BIGFUNCTION()
[1] "DATAFRAME"
   a b
1 1 4
2 2 5
3 3 6

Duncan Murdoch


> BIGFUNCTION	<- function()
> 	{
> 	DATAFRAME	<- [some commands to create a dataframe]
> 	MYFUNCTION(DATAFRAME)
> 	}
> MYFUNCTION	<- function(DATAFRAME)
> 	{
> 	print(ls())
> 	exists("DATAFRAME")
> 	source("myfile", local=T)
> 	}
> 
> The file "myfile" contains the following:
> 	print(DATAFRAME)
> 
> When I execute BIGFUNCTION from the command line, R reports:
> 	Error in print(DATAFRAME) : object "DATAFRAME" not found
> 	Calls: BIGFUNCTION ... source -> eval.with.vis -> eval.with.vis ->  
> print -> head
> 	Execution halted
> However, the "print(ls())" command has just listed the existence of  
> DATAFRAME and "exists(DATAFRAME) return TRUE
> So, I am at a loss as to why ls() and "exists" see the object but  
> print(DATAFRAME) command does not.
> 
> I tried "local=F" in the source command to no avail.
> I also replaced "print(DATAFRAME)" with "print(str(DATAFRAME))" with  
> the same outcome.
> I assume that this is an error as to how I am managing environments  
> but I cannot figure out a solution.  Any help would be appreciated.
> 
> Dennis
> 
> 
> 
> Dennis Fisher MD
> P < (The "P Less Than" Company)
> Phone: 1-866-PLessThan (1-866-753-7784)
> Fax: 1-415-564-2220
> www.PLessThan.com
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list