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

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


Duncan Murdoch <dmurdoch at pair.com> writes:

> On Tue, 6 Apr 2004 14:18:42 +0000 (UTC), you wrote:
> 
> >Robin Hankin <rksh <at> soc.soton.ac.uk> writes:
> >> R> a <- matrix(1:9,3,3)
> >> But the following caught me off-guard:
> >> R> a <- matrix(1:9,3,3)
> >> R> a[a%%2==1] %+=% 1000*(1:5)
> >
> >How about this way:
> >
> >> a <- matrix(1:9,3,3)
> >> "plus<-" <- function(a,value) a+value
> >> plus(a[a%%2==1]) <- 1000*(1:5)
> >> a
> >     [,1] [,2] [,3]
> >[1,] 1001    4 4007
> >[2,]    2 3005    8
> >[3,] 2003    6 5009
> 
> Wouldn't a clearer syntax to follow be Pascal's?  I.e.
> 
> inc <- function(a, b) {
>     eval.parent(substitute(a <- a + b))
> }
> 
> Then in order to increment x[3], you'd use
> 
> inc(x[3], 1)
> 

But that's not kosher in functional programming languages where you
expect function calls not to modify their arguments, is it? (OK, so
assignment is also a function call as is setq in Lisp, but we have
syntactic sugar to cover that. That's what was nice about %<-%.)

BTW, you can also (but I'm not sure you should!) do

"+<-" <- function(x,value) x + value
x     <- c(2,3)
+x[1] <- 3

        -p

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