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

Robin Hankin rksh at soc.soton.ac.uk
Tue Apr 6 15:36:32 CEST 2004


Some time ago, Peter Dalgaard made the wonderful suggestion to define

"%+=%" <- function(a,b) {eval.parent(substitute(a <- a + b)) }


Which I use (R-1.8.1) as follows:

R> a <- matrix(1:9,3,3)
R> a[a%%2==1] %+=% (1000*(1:5))
R> a
      [,1] [,2] [,3]
[1,] 1001    4 4007
[2,]    2 3005    8
[3,] 2003    6 5009
R>

which is what I want.  But the following caught me off-guard:


R> a <- matrix(1:9,3,3)
R> a[a%%2==1] %+=% 1000*(1:5)
[1] 1001 2006 3015 4028 5045
R> a
      [,1] [,2] [,3]
[1,] 1001    4 1007
[2,]    2 1005    8
[3,] 1003    6 1009
R>

Why the difference when I remove the brackets?
And how is the vector that is printed in the unbracketed version determined?
(why is this printed anyway? doing "a[a%%2==1] %+=% 1000" doesnt
print anything).

Is there a better way to code up %+=%  ?

-- 
Robin Hankin
Uncertainty Analyst
Southampton Oceanography Centre
SO14 3ZH
tel +44(0)23-8059-7743
initialDOTsurname at soc.soton.ac.uk (edit in obvious way; spam precaution)




More information about the R-help mailing list