[R] scope of variables in R

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue Mar 31 21:41:52 CEST 2009


Stavros Macrakis wrote:
> On Tue, Mar 31, 2009 at 7:10 AM, <mauede at alice.it> wrote:
>
>   
>> I need to allocate (using C nomenclature) a set of "global" variables, some
>> integer scalars and some double vectors.
>> ...
>>     
>
> My question is: how can I have R interpreter allocate "global"variables
>   
>> visible and accessible by all the functions in the same file ?
>>
>>     
>
> You don't need to explicitly allocate variables in R.  Assigning to them
> will create them.
>
> If you want to modify a global variable within a function, you need to use
> the <<- assignment operator instead of the <- assignment operator.  In
> effect, the <- assignment operator *always* refers to a local variable, and
> creates one if one does not exist yet.
>
> I do not know how to limit the visibility of a variable to "functions in the
> same file". On the other hand, you can limit the visibility of a variable to
> a group of functions quite straightforwardly:
>
> local({
>    global1 <- 3     # allocated within the local scope with <-
>    global2 <- 4
>
>    fun1 <<- function(...) ... global1 ...   # lexical scoping; refers to
> global1
>         # must assign fun1 with <<- so it is created in the global scope
> })
>   

this is where multiple assignment might be your friend:

    source('http://miscell.googlecode.com/svn/rvalues/rvalues.r')
    c(foo, bar, gee) := local({
        shared = 0
        foo = function() shared <<- 0
        bar = function(bar) shared <<- bar
        gee = function() print(shared)
        c(foo, bar, gee) })

now you have three functions in the scope where you evaluate the code,
all of them have access to the shared variable 'shared', and the
variable is inaccessible (roughly, unless you know how to access it)
otherwise than by these functions:

    gee()
    # 0
    bar(1)
    gee()
    # 1
    foo()
    gee()
    # 0

would this be what you want?

> But I suspect you don't need this level of complexity.
>
> All that being said, programming with global variables makes certain classes
> of bug much more likely....

... in a language like r, that heavily relies on setting global
variables (par(), options(), ...).


vQ




More information about the R-help mailing list