Look at Syntax on R-help apropos operators precedence A.S. ---------------------------- Alessandro Semeria Models and Simulations Laboratory Montecatini Environmental Research Center (Edison Group), Via Ciro Menotti 48, 48023 Marina di Ravenna (RA), Italy Tel. +39 544 536811 Fax. +39 544 538663 E-mail: alessandro.semeria at cramont.it
Some time ago, Peter Dalgaard made the wonderful suggestion to define "%+=%" <- function(a,b) {eval.parent(substitute(a <- a + b)) } Which I use (R-1.8.1) as follows: R> a <- matrix(1:9,3,3) R> a[a%%2==1] %+=% (1000*(1:5)) R> a [,1] [,2] [,3] [1,] 1001 4 4007 [2,] 2 3005 8 [3,] 2003 6 5009 R> which is what I want. But 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? 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 %+=% ? -- Robin Hankin Uncertainty Analyst Southampton Oceanography Centre SO14 3ZH tel +44(0)23-8059-7743 initialDOTsurname at soc.soton.ac.uk (edit in obvious way; spam precaution)
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>
Value in an internal variable of a command "function", have a look on R-help apropos "function". A.S. ---------------------------- Alessandro Semeria Models and Simulations Laboratory Montecatini Environmental Research Center (Edison Group), Via Ciro Menotti 48, 48023 Marina di Ravenna (RA), Italy Tel. +39 544 536811 Fax. +39 544 538663 E-mail: alessandro.semeria at cramont.it