[R] %+=% and eval.parent()
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Tue Apr 6 14:56:37 CEST 2004
Robin Hankin <rksh at soc.soton.ac.uk> writes:
> Some time ago, Peter Dalgaard made the wonderful suggestion to define
>
> "%+=%" <- function(a,b) {eval.parent(substitute(a <- a + b)) }
...
> 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).
You're getting caught out by operator precedence:
a[a%%2==1] %+=% 1000*(1:5)
is effectively
(a[a%%2==1] %+=% 1000)*(1:5)
because %foo% operators have higher precedence than * (and much higher
than ordinary assignment)
> Is there a better way to code up %+=% ?
Not really. You could hack the parser, but from within R, there is no
way to set parser precedence.
--
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