[Rd] surprising behaviour of names<-
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue Mar 10 18:58:02 CET 2009
Stavros Macrakis wrote:
>>> (B) you cannot (easily) predict whether or not x will be modified
>>> destructively
>>>
>> that's fine, thanks, but i must be terribly stupid as i do not see how
>> this explains the examples above. where is the x used by something else
>> in the first example, so that 'names<-'(x, 'foo') does *not* modify x
>> destructively, while it does in the other cases?
>>
>> i just can't see how your explanation fits the examples -- it probably
>> does, but i beg you show it explicitly.
>>
>
> I think the following shows what Peter was referring to:
>
> In this case, there is only one pointer to the value of x:
>
> x <- c(1,2)
>
>> "names<-"(x,"foo")
>>
> foo <NA>
> 1 2
>
>> x
>>
> foo <NA>
> 1 2
>
> In this case, there are two:
>
>
>> x <- c(1,2)
>> y <- x
>> "names<-"(x,"foo")
>>
> foo <NA>
> 1 2
>
>> x
>>
> [1] 1 2
>
>> y
>>
> [1] 1 2
>
that is and was clear to me, but none of my examples was of the second
form, and hence i think peter's answer did not answer my question.
what's the difference here:
x = 1
'names<-'(x, 'foo')
names(x)
# NULL
x = c(foo=1)
'names<-'(x, 'foo')
names(x)
# "foo"
certainly not something like what you show. what's the difference here:
x = 1
'names<-'(x, 'foo')
names(x)
# NULL
x = 1:2
'names<-'(x, c('foo', 'bar'))
names(x)
# "foo" "bar"
certainly not something like what you show.
> It seems as though `names<-` and the like cannot be treated as R
> functions (which do not modify their arguments) but as special
> internal routines which do sometimes modify their arguments.
>
they seem to behave somewhat like macros:
'names<-'(a, b)
with the destructive 'names<-' is sort of replaced with
a = 'names<-'(a, b)
with a functional 'names<-'. but this still does not explain the
incoherence above. my problem was and is not that 'names<-' is not a
pure function, but that it sometimes is, sometimes is not, without any
obvious explanation. that is, i suspect (not claim) that the behaviour
is not a design feature, but an incident.
vQ
More information about the R-devel
mailing list