[R] %+=% and eval.parent()
Prof Brian Ripley
ripley at stats.ox.ac.uk
Fri Apr 9 13:55:13 CEST 2004
On 7 Apr 2004, Peter Dalgaard wrote:
> Robin Hankin <rksh at soc.soton.ac.uk> writes:
>
> > Hi again everybody.
> >
> > Yesterday I had a problem with c-style "+=" functions. One suggestion
> > was to define
> >
> > R> "plus<-" <- function(x,value){x+value}
> >
> > Then
> >
> > R> a <- matrix(1:9,3,3)
> > R> plus(a[a%%2==1]) <- 1000
> >
> > works as desired.
> >
> >
> > QUESTION: why does this behave differently:
> >
> >
> > R> "plus<-" <- function(x,y){x+y}
> > R> a <- matrix(1:9,3,3)
> >
> > R> plus(a[a%%2==1]) <- 1000
> > Error in "plus<-"(`*tmp*`, value = 1000) :
> > unused argument(s) (value ...)
> > R>
> >
> > The only change seems to be changing the second argument from "value"
> > to "y". Why does this affect anything? Where do I look for
> > documentation on things like "plus<-" ?
>
> These assignment functions work basically by
>
> plus(x) <- foo
>
> getting internally transcribed as
>
> x <- "plus<-"(x, value=foo)
>
> (actually, there's an intermediate alias for the target to avoid
> multiple evaluation; this is what shows up as *tmp*, but you're not
> supposed to know that...)
>
> The use of the keyword matching form was prompted by some problems
> with indexing functions that take a variable number of indices in
> addition to x. (Think "[<-"(x,i,value) vs. "[<-"(x,i,j,value) and the
> hoops you have to jump through when the value gets passed in the j
> argument.) However, keyword matching of course implies that you need
> to use the matching keyword in the function definition.
>
> This *should* be somewhere in the R Language Definition, although I'm
> not sure it is actually there. Or the blue book, although I suspect
> that S v.3 actually used positional matching (and jumped through
> hoops).
It did. This is in the FAQ, 3.2.3:
* In R, the argument of a replacement function which corresponds to the
right hand side must be named `value'. E.g., `f(a) <- b' is evaluated
as `a <- "f<-"(a, value = b)'. S always takes the last argument,
irrespective of its name.
I seem to recall I discovered the discrepancy in ca 1998.
R-lang is minimalist about what it calls `assignment functions', most of
the time.
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list