[R] Truly Global Variables

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jan 22 23:05:51 CET 2011


On Sat, Jan 22, 2011 at 8:17 AM, Duncan Murdoch
<murdoch.duncan at gmail.com> wrote:
> On 11-01-22 3:06 AM, Lui ## wrote:
>>
>> Hello everybody,
>>
>> I have a problem that is bothering me for  quite a while now and I
>> don't know the answer... I want to create global variables (out of a
>> function) which I can access from all other functions... But somehow
>> that does not work too well. Attached some code for an example:
>>
>> function_called<- function (){
>>        result = globalvariable*globalvariable
>>        print(result)
>>
>>        }
>>
>> function_calls<- function(){
>>        assign("globalvariable",10,pos=-1,envir=as.environment(pos))
>
> This line doesn't make sense.  Why specify both pos and envir?  I would have
> used envir=globalenv() to do what you want; the help page indicates that
> pos=globalenv() is preferred by whoever wrote it.  But don't use both.
>
> However, an even simpler approach is simply
>
> globalvariable <<- 10
>
> This will search back through the environments associated with the
> function_calls function (not the call stack!) for a variable named
> globalvariable, and make the assignment to it.  If none exists, it will use
> the global environment.
>

Or a bit safer:

   assign("globalvariable", 10, .GlobalEnv)

Note that this type of code is sometimes an attempt to get into object
oriented programming through the back door.  You might just want to
make it explicit.  The proto package will let you do that.  Below we
define a proto object, p, with components function_called and
function_calls and then later, within function_calls, we create a
third component of p called variable.

library(proto)

p <- proto(function_called = function (.) {
       result = .$variable * .$variable
       print(result)
       },
       function_calls = function(.) {
       .$variable <- 10
       .$function_called()
       }
)

p$function_calls()



-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list