[Rd] surprising behaviour of names<-

Berwin A Turlach berwin at maths.uwa.edu.au
Thu Mar 12 14:35:08 CET 2009


On Thu, 12 Mar 2009 10:53:19 +0100
Wacek Kusnierczyk <Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:

> well, ?'names<-' says:
> 
> "
> Value:
>      For 'names<-', the updated object. 
> "
> 
> which is only partially correct, in that the value will sometimes be
> an updated *copy* of the object.

But since R supposedly uses call-by-value (though we know how to
circumvent that, don't we?) wouldn't you always expect that a copy of
the object is returned?
 
> > And the R Language manual (ignoring for the moment that it is a
> > draft and all that), 
> 
> since we must...
> 
> > clearly states that 
> >
> > 	names(x) <- c("a","b")
> >
> > is equivalent to
> > 	
> > 	'*tmp*' <- x
> >          x <- "names<-"('*tmp*', value=c("a","b"))
> >   
> 
> ... and?  

This seems to suggest that in this case the infix and prefix syntax
is not equivalent as it does not say that 
	names(x) <- c("a","b")
is equivalent to
	x <- "names<-"(x, value=c("a","b"))
and I was commenting on the claim that the infix syntax is equivalent
to the prefix syntax.

> does this say anything about what 'names<-'(...) actually
> returns?  updated *tmp*, or a copy of it?

Since R uses pass-by-value, you would expect the latter, wouldn't
you?  If you entertain the idea that 'names<-' updates *tmp* and
returns the updated *tmp*, then you believe that 'names<-' behaves in a
non-standard way and should take appropriate care.

And the fact that a variable *tmp* is used hints to the fact that
'names<-' might have side-effect.  If 'names<-' has side effects,
then it might not be well defined with what value x ends up with if
one executes:
	x <- 'names<-'(x, value=c("a","b"))  

This is similar to the discussion what value i should have in the
following C snippet:
	i = 0;
 	i += i++;
 
[..]
> > I am not sure whether R ever behaved in that way, but as Peter
> > pointed out, this would be quite undesirable from a memory
> > management and performance point of view.  
> 
> why?  you can still use the infix names<- with destructive semantics
> to avoid copying. 

I guess that would require a rewrite (or extension) of the parser.  To
me, Section 10.1.2 of the Language Definition manual suggests that once
an expression is parsed, you cannot distinguish any more whether
'names<-' was called using infix syntax or prefix syntax.

Thus, I guess you want to start a discussion with R Core whether it is
worthwhile to change the parser such that it keeps track on whether a
function was used with infix notation or prefix notation and to
provide for most (all?) assignment operators implementations that use
destructive semantics if the infix version was used and always copy if
the prefix notation is used. 

Cheers,

	Berwin



More information about the R-devel mailing list