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

Duncan Murdoch dmurdoch at pair.com
Wed Apr 7 13:21:08 CEST 2004


On Tue, 6 Apr 2004 14:18:42 +0000 (UTC), you wrote:

>Robin Hankin <rksh <at> soc.soton.ac.uk> writes:
>> R> a <- matrix(1:9,3,3)
>> But the following caught me off-guard:
>> R> a <- matrix(1:9,3,3)
>> R> a[a%%2==1] %+=% 1000*(1:5)
>
>How about this way:
>
>> a <- matrix(1:9,3,3)
>> "plus<-" <- function(a,value) a+value
>> plus(a[a%%2==1]) <- 1000*(1:5)
>> a
>     [,1] [,2] [,3]
>[1,] 1001    4 4007
>[2,]    2 3005    8
>[3,] 2003    6 5009

Wouldn't a clearer syntax to follow be Pascal's?  I.e.

inc <- function(a, b) {
    eval.parent(substitute(a <- a + b))
}

Then in order to increment x[3], you'd use

inc(x[3], 1)

etc.

Duncan Murdoch




More information about the R-help mailing list