[R] %+=% and eval.parent()

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Apr 7 10:52:02 CEST 2004


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).

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list