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

Duncan Murdoch dmurdoch at pair.com
Tue Apr 6 14:59:38 CEST 2004


On Tue, 6 Apr 2004 13:36:32 +0000, Robin Hankin <rksh at soc.soton.ac.uk>
wrote :

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

Looks to me like an operator precedence issue.  Your line is
equivalent to 

(a[a%%2==1] %+=% 1000)*(1:5)

This is described in the Language Manual, in Parser | Expressions |
Infix and prefix operators (section 10.4.2 in the PDF version).  The
user defined %xyz% operators have precedence just above * and /.

>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 %+=%  ?

Not really.  You can't control operator precedence in R. 

Duncan Murdoch




More information about the R-help mailing list