[R] Variable scope in functions - best practices

Enrico Schumann enricoschumann at yahoo.de
Sun Jul 24 18:46:10 CEST 2011


Hi Noah,
 
you could assign your "global variables" into an environment. Then make it
the environment of your function, and use the `<<-` operator (or 'assign').

An example:

> myData <- new.env()
> myData$i <- 0
> iPlusOne <- function() i <<- i+1
> environment(iPlusOne) <- myData
> ls()
[1] "iPlusOne" "myData"  
> ls(myData)
[1] "i"


> myData$i
[1] 0
> iPlusOne()
> myData$i
[1] 1
> iPlusOne()
> myData$i
[1] 2

Regards,
Enrico


> -----Ursprüngliche Nachricht-----
> Von: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] Im Auftrag von Noah Silverman
> Gesendet: Sonntag, 24. Juli 2011 18:14
> An: r-help at r-project.org
> Betreff: [R] Variable scope in functions - best practices
> 
> 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?
> 
> Thanks!
> 
> --
> Noah Silverman
> UCLA Department of Statistics
> 8117 Math Sciences Building
> Los Angeles, CA 90095
> 
> ______________________________________________
> 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