[Rd] surprising behaviour of names<-

Berwin A Turlach berwin at maths.uwa.edu.au
Fri Mar 13 16:47:55 CET 2009

On Fri, 13 Mar 2009 11:43:55 +0100
Wacek Kusnierczyk <Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:

> Berwin A Turlach wrote:
> > And it is documented behaviour.  
> sure!

Glad to see that we agree on this.

> > Read section 2.1.10 ("Environments") in the R
> > Language Definition, 
> haven't objected to that.  i object to your 'r uses pass by value',
> which is only partially correct.

Well, I used qualifiers and did not stated it categorically. 
> >> and actually, in the example we discuss, 'names<-' does *not*
> >> return an updated *tmp*, so there's even less to entertain.  
> >>     
> >
> > How do you know?  Are you sure?  Have you by now studied what goes
> > on under the hood?
> yes, a bit.  but in this example, it's enough to look into *tmp* to
> see that it hasn't got the names added, and since x does have names,
> names<- must have returned a copy of *tmp* rather than *tmp* changed:
>     x = 1
>     tmp = x
>     x = 'names<-'(tmp, 'foo')
>     names(tmp)
>     # NULL

Indeed, if you type these two commands on the command line, then it is
not surprising that a copy of tmp is returned since you create a
temporary object that ends up in the symbol table and persist after the
commands are finished.

Obviously, assuming that R really executes 
	*tmp* <- x
	x <- "names<-"('*tmp*', value=c("a","b"))
under the hood, in the C code, then *tmp* does not end up in the symbol
table and does not persist beyond the execution of 
	names(x) <- c("a","b")

This looks to me as one of the situations where a value of 1 is used
for the named field of some of the objects involves so that a copy can
be avoided.  That's why I asked whether you looked under the hood.

> you suggested that "One reads the manual, (...) one reflects and
> investigates, ..."

Indeed, and I am not giving up hope that one day you will master this

> -- had you done it, you wouldn't have asked the  question.

Sorry, I forgot that you have a tendency to interpret statements
extremely verbatim and with little reference to the context in which
they are made.  I will try to be more explicit in future.

> >> for fun and more guesswork, the example could have been:
> >>
> >>     x = x
> >>     x = 'names<-'(x, value=c('a', 'b'))
> >>     
> >
> > But it is manifestly not written that way in the manual; and for
> > good reasons since 'names<-' might have side effects which invokes
> > in the last line undefined behaviour.  Just as in the equivalent C
> > snippet that I mentioned.
> i just can't get it why the manual does not manifestly explain what
> 'names<-' does, and leaves you doing the guesswork you suggest.

As I said before, patched to documentation are also welcome.

Best wishes,

More information about the R-devel mailing list