[R] assigment operator question

Thomas Lumley tlumley at uw.edu
Sun Apr 8 23:55:03 CEST 2012


On Sun, Apr 8, 2012 at 11:57 AM, Duncan Murdoch
<murdoch.duncan at gmail.com> wrote:
> On 12-04-07 4:51 PM, Henrik Bengtsson wrote:
>>
>> On Sat, Apr 7, 2012 at 1:30 PM, Mark Heckmann<mark.heckmann at gmx.de>
>>  wrote:
>>>
>>> Hello,
>>>
>>> using the<<- assignment operator I do not understand why the following
>>> does not work.
>>>
>>> l<<- list()
>>> l
>>> list()
>>> l$arg1<<- "test"
>>> error in l$arg1<<- "test" : Objekt 'l' not found
>>>
>>> ?"<<-" says:  "The operators<<- and ->>  cause a search to made through
>>> the environment for an existing definition of the variable being assigned.
>>> If such a variable is found (and its binding is not locked) then its value
>>> is redefined, otherwise assignment takes place in the global environment. "
>>>
>>> Still I do noch understand why the above does not work. The object l is
>>> in the global environment. Can someone explain it to me?
>>
>>
>> Yes, the object 'l' is in the global environment, but 'l$arg1' is not,
>> cf. exists("l$arg1") and exists("l").  Instead, this works:
>
>
> I don't think that is the problem:  <<- normally works with complex
> assignments.  I think the problems are
>
>  - Mark was working at top level in the console
>  - The documentation isn't clear about what happens in that case.
>  - R is inconsistent between simple and complex assignments with <<-.
>
> The <<- operator is designed to be used in a function, and it makes an
> assignment in the environment of the function, not in the local evaluation
> frame.  If it can't find a variable there, it assigns into the global
> environment.  So if the l$arg1 <<- "test" was a line in a function,
> everything would have worked as expected.
>
> When you use it at the top level, it tries looking in the parent of the
> global environment, its parent, and so on, back to the empty environment at
> the root of all the namespaces.  If you happened to use a name like "mean"
> which exists, it will try to assign to that object (and fail, because that
> binding is locked).
>
> If you pick a name that doesn't exist, then R is inconsistent.  If you're
> doing a simple assignment like
>
> l <<- 5
>
> it will be done in the global environment, creating a new variable if
> necessary.  If you're doing a complex assignment like
>
> l$arg1 <- "test"
>
> it will just fail, there's no global environment fallback.
>
> I don't think this inconsistency is really worth fixing, since <<- is
> designed for use in functions.  There really isn't any use for it at the top
> level.
>
> But maybe all of this should be documented.
>

There's quite a bit of detail in section 3.4 of the R Language
Definition, though it's focused on subscripting superassignments.   It
even covers pathological cases such as  x[is.na(x)] <<- 0

  -thomas

-- 
Thomas Lumley
Professor of Biostatistics
University of Auckland



More information about the R-help mailing list