[R] recursive functions and global variables

David A Richmond richmond at saintmarys.edu
Mon Oct 15 03:00:49 CEST 2001

Hi again, 
	OK, I figured out how to get "new.env()" and "environment <-"
(thanks for the advice!) to allow called functions to access the variables
_created_ in the calling functions, but not the variables passed to the
calling function in the first place. For example, consider:

test <- function(x) {
	new.env-> storage
	b <- x^2

test2 <- function(e) {
	environment <- e
	cat("x =",x,"\n")
	cat("b =",b,"\n")


This fails in 'cat("x =",x,"\n")' because test2() doesn't know what "x" is
because it wasn't created in test(), but rather was a value passed to
test. Is there any way to get test2() to recognize this variable? (I know
I could simply make a copy x2 <- x in test(), but I'm trying to save
space, in my final application the 'x' will be a big array.


On Sun, 14 Oct 2001, Thomas Lumley wrote:

> On Sun, 14 Oct 2001, David A Richmond wrote:
> > Hi,
> > 	I am trying to write a recursive routine which passes some
> > variables through the function calls but also refers to some global
> > variables. I need the global variables because they are very big (n by n
> > matrices where n is <= 1000) and I don't have the huge amount of memory
> > needed to spawn dozens of copies of these matrices. The problem seems to
> > be that while variables in the root environment of R are global, variables
> > created in a function func1() are not available in functions called by
> > func1(). (See the example below.) So I need a way to create some variables
> > at the root level of a function that are available at any level
> > 'underneath' the base function level. Note also that I want to be able to
> > modify elements that are at a higher level as well.
> >
> You probably want to use a named environment. There's an example in the
> `Programmer's Niche' section of the 2nd R newsletter, on the R home page.
> Basically, you create an environment like
>    storage<-new.env()
> and pass it down through your functions. You can then use get() and
> assign() to retrieve and modify objects in this environment.
> This is often the R way to handle issues for which S-PLUS programmers
> would use 'frame 0' and 'frame 1'.
> 	-thomas
> Thomas Lumley			Asst. Professor, Biostatistics
> tlumley at u.washington.edu	University of Washington, Seattle

|David Richmond                It works on a          |      
+ Dept. of Sociology          complex scientific      + 
|Saint Mary's College          principle, known as    |  
+ Notre Dame, IN 46556               "pot luck."      +
|219-284-4517                    - The Doctor         |

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list