[R] += assignment operator
David Brahm
brahm at alum.mit.edu
Tue Nov 11 18:58:24 CET 2003
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.
--
-- David Brahm (brahm at alum.mit.edu)
More information about the R-help
mailing list