[Rd] surprising behaviour of names<-

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Thu Mar 12 16:12:03 CET 2009


Simon Urbanek wrote:
>
> On Mar 11, 2009, at 10:52 , Simon Urbanek wrote:
>
>> Wacek,
>>
>> Peter gave you a full answer explaining it very well. If you really
>> want to be able to trace each instance yourself, you have to learn
>> far more about R internals than you apparently know (and Peter hinted
>> at that). Internally x=1 an x=c(1) are slightly different in that the
>> former has NAMED(x) = 2 whereas the latter has NAMED(x) = 0 which is
>> what causes the difference in behavior as Peter explained. The reason
>> is that c(1) creates a copy of the 1 (which is a constant
>> [=unmutable] thus requiring a copy) and the new copy has no other
>> references and thus can be modified and hence NAMED(x) = 0.
>>
>
> Errata: to be precise replace NAMED(x) = 0 with NAMED(x) = 1 above --
> since NAMED(c(1)) = 0 and once it's assigned to x it becomes NAMED(x)
> = 1 -- this is just a detail on how things work with assignment, the
> explanation above is still correct since duplication happens
> conditional on NAMED == 2.

there is an interesting corollary.  self-assignment seems to increase
the reference count:

    x = 1;  'names<-'(x, 'foo'); names(x)
    # NULL

    x = 1;  x = x;  'names<-'(x, 'foo'); names(x)
    # "foo"

vQ



More information about the R-devel mailing list