[R] scope of variables in R

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Apr 1 10:11:10 CEST 2009


Stavros Macrakis wrote:
> On Tue, Mar 31, 2009 at 3:41 PM, Wacek Kusnierczyk <
> Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:
>
>   
>> Stavros Macrakis wrote:
>>     
>>> ...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(), ...).
>>
>>     
>
> Yes, par, options, etc. are problematic, too, especially since there's no
> easy way I know of to make them local (like dynamic binding in old Lisps).
>   

indeed, i too was thinking about something like perl's local:

    print $$;
    # 123456
    { local $$;
       print $$; }
    # (empty string)

or fluid-let in scheme.

i don't know of any construct in r that would localize global variables
in this manner, but for options, par, etc., you do have an option, the
(arguably ugly) idiom with storing the previous value and restoring it
on exit:

    print(getOption('digits'))
    # 7

    local({
       options = options(digits=1)
       on.exit(options(options))
       print(getOption('digits')) })
    # 1

    print(getOption('digits'))
    # 7

it's like manually localizing a global variable.

vQ




More information about the R-help mailing list