David Brahm <brahm at alum.mit.edu> writes:
> The thread "Finding the name ob an object" gave me an idea about
how to write
> an assignment operator like C's "+=":
>
> "%+=%" <- function(a, b) {
> as <- deparse(substitute(a))
> bs <- deparse(substitute(b))
> st <- paste(as, "<-", as, "+", bs)
> eval.parent(parse(text=st), 2)
> }
>
> R> xx <- matrix(1:9, 3,3)
> R> xx[2, which(xx[2, ] < 6)] %+=% 100
> R> xx
> [,1] [,2] [,3]
> [1,] 1 4 7
> [2,] 102 105 8
> [3,] 3 6 9
>
> Anyone have any better ideas on building this kind of operator? It would
be
> better if the condition [which(...)] were only evaluated once. Bonus
points if
> you can make %*=%, %-=%, etc. all in one fell swoop.
I don't think either of those are realistically possible at the R
level. Even at the C level, it would probably be a hack, but so is the
way we handle complex assignments (like foo$i[j][[k]] <- fum) already.
However, paste() always looks wrong to me:
"%+=%" <- function(a, b) eval.parent(substitute(a <- a + b))
--
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