[R] Variable scope in functions - best practices

Thomas Lumley tlumley at uw.edu
Sun Jul 24 23:11:14 CEST 2011


On Mon, Jul 25, 2011 at 4:14 AM, Noah Silverman <noahsilverman at ucla.edu> wrote:
> Hi,
>
> I'm working on coding some more complex things in R and have need to break much of the logic into functions.
>
> I have several "global" variables that I want to change with a given function.  (The variable has a different value after the function is called.)
>
> In other languages like C, this is simple.  However, in R, if a function changes a variable, that change only occurs in the frame of that function.  So, when the function returns, the old value is still there.
>
> Of course, I could just have the function return the value, but some functions change 5-6 variables.  So, I could have a function return a list, and then parse that list every time, but that seems like an excessive amount of overhead.  (Especially as some functions may be called many many times.)
>
> How have some of you handled this?  Is there a "best practices" way?
>


Usually I would handle this by returning a list.  It's not that much overhead.

If you have a set of functions that share variables (like a C static
variable) you can use lexical scope and <<- to make changes. The demos
in the tcltk package do this.

You can also use a scratchpad environment and pass it around.  Since
environments are passed by references, changes made to that
environment inside a function will stay changed.

e<-new.env()
e$storage<-0
f<-function(i, scratchpad){
   scratchpad$storage<-scratchpad$storage+i
   scratchpad$storage
}
g<-function(i, scratchpad){
   scratchpad$storage<-scratchpad$storage-i
   scratchpad$storage
}

f(1,e)
g(2,e)
f(3,e)
g(4,e)

    -thomas




-- 
Thomas Lumley
Professor of Biostatistics
University of Auckland



More information about the R-help mailing list