Hi I'd like to be able to write a simple 'increment' function (like inc in pascal or ++ in C++) that takes the argument and increments it 'permanently' ie so that z<-1; inc(z) # no assignment; z #2 I can see how to do it with a global variable but that is not what I want - I want to modify the object that is the actual argument.. I have looked at assign(), << etc .. I am not sure where to go next. I thought I could possibly do it by reference to the calling environment and tried> incfunction(a){ eval.parent(a<-a+1,1) }> z<-1 > inc(z)[1] 2> z[1] 1>no good Is what I want to do possible? (I realize that it is possibly inadvisable as there would be no obvious way of knowing from the function definition that it modified its arguments) thanks John Aitchison -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html Send "info", "help", or "[un]subscribe" (in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
Prof Brian D Ripley
2001-Mar-02 07:43 UTC
[R] inc function .. more generally, var arguments
On Fri, 2 Mar 2001, John Aitchison wrote:> > Hi > > I'd like to be able to write a simple 'increment' function (like inc in > pascal or ++ in C++) that takes the argument and increments it > 'permanently' ie so that z<-1; inc(z) # no assignment; z #2 > > I can see how to do it with a global variable but that is not what I want - > I want to modify the object that is the actual argument.. I have looked > at assign(), << etc .. I am not sure where to go next. > > I thought I could possibly do it by reference to the calling environment > and tried > > > inc > function(a){ eval.parent(a<-a+1,1) } > > z<-1 > > inc(z) > [1] 2 > > z > [1] 1 > > > no good > > Is what I want to do possible? (I realize that it is possibly inadvisable > as there would be no obvious way of knowing from the function > definition that it modified its arguments)This is precisely exercise 4.4 of Venables & Ripley (1997). There is an answer online at http://www.stats.ox.ac.uk/pub/MASS/VR2ans.pdf for S: R could be slightly different. -- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272860 (secr) Oxford OX1 3TG, UK Fax: +44 1865 272595 -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html Send "info", "help", or "[un]subscribe" (in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._