?cumsum > system.time({ z <- NULL ; for (i in 1:1000) z <- c(z, sum((1:i)**2)) }) [1] 0.04 0.00 0.04 NA NA > system.time( zz <- cumsum((1:1000)**2) ) [1] 0 0 0 NA NA > all.equal(z,zz) [1] TRUE
------------------------------------------------------------------- Jacques VESLOT CNRS UMR 8090 I.B.L (2ème étage) 1 rue du Professeur Calmette B.P. 245 59019 Lille Cedex Tel : 33 (0)3.20.87.10.44 Fax : 33 (0)3.20.87.10.31 http://www-good.ibl.fr ------------------------------------------------------------------- Paul Chatfield a écrit : > Hi - I'm trying to avoid using a 'for' loop due to inefficiency and instead > use a function (and ultimately tapply as I'm working on a matrix) but I can't > figure out how to get 'function' to take the variables as anything other than > vectors for example > > aa<-0 > x<-1:4 > test.fun<-function(x) > {aa<-(x*x +aa) > return(aa)} > test.fun(1:4) > > This code returns 'aa' as 1 4 9 16, but I'd like it to return aa as 1 5 14 > 30 taking into consideration that I've just calculated aa for x=1. Aside > from using loops, is there not a simple way of telling R to work out x for > consecutive values? > > thanks > > Paul Chatfield > > > Send instant messages to your online friends http://uk.messenger.yahoo.com > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html > ______________________________________________ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html