> -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of OKB (not okblacke) > Sent: Wednesday, September 16, 2009 6:04 PM > To: r-h...@stat.math.ethz.ch > Subject: Re: [R] Generalized cumsum? > > David Winsemius wrote: > > >> No, Reduce reduces an entire vector to a single value by > >> repeatedly > >> combining adjacent elements. I'm looking to convert a vector to > >> another vector where each element is some arbitrary aggregating > >> function applied to the first n elements of the vector. > > > > Yes. You need to look again: > > > > accumulate=FALSE by default, but is subject to change.- > > Ah, sorry. Yes, you're right. However, this still > doesn't satisfy > my needs, because since Reduce successively combines one element at a > time, it doesn't work for functions that don't self-compose > transitively. For instance: > > > Reduce(mean, c(1,2,3,4), accumulate=T) > [1] 1 1 1 1 > > but I want > > > cumapply(mean, c(1,2,3,4)) > [1] 1 1.5 2 2.5 > > Is there anything this general?
You can wrap mean() with a function that maintains sufficient data that you can update the estimate. I don't think this can be automated, aside from the trivial method of retaining all the data up until now so you can compute the statistic from scratch each time. Doesn't median require almost this approach? (median could keep the accumulated data in sorted order to make updates faster but it needs all the data.) Most robust techniques don't have update procedures because they depend on order statistics of functions of the data. Combining functions like seq, cumsum, cummax, and filter will cover a lot of common cases. > cummean<-function(x)cumsum(x)/seq_along(x) > cummean(1:4) [1] 1.0 1.5 2.0 2.5 Bill Dunlap TIBCO Software Inc - Spotfire Division wdunlap tibco.com > > Thanks, > -- > --OKB (not okblacke) > Brendan Barnwell > "Do not follow where the path may lead. Go, instead, where there is > no path, and leave a trail." > --author unknown > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.