[R] Function similar to cumsum/cumprod

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Tue Sep 22 16:42:23 CEST 2009


For the case of the mean, you can use the following:

cummean <- function (x) cumsum(x) / seq_len(length(x))

for more a general function, one option is

cumFUN <- function (x, FUN = mean) {
    sapply(seq_len(length(x)), function (i) FUN(x[1:i]))
}

# Examples:
x <- rnorm(100)
cummean(x)
cumFUN(x)
cumFUN(x, sd)


I hope it helps.

Best,
Dimitris


Sergey Goriatchev wrote:
> Hello, everyone
> 
> I wonder if there is in R somewhere a function similar to cumsum().
> The function calculates a statistic (say mean or standard deviation)
> buy adding consequtively one more data point.
> 
> So, say I have a timeseries of 100 observations.
> I start by calculating mean of first 30 observations
> Then I add one observation and calculate mean of 31 observations
> Then I add one more observation and calculate mean of 32 observation,
> and so on until the end
> 
> Is there a function like that in R?
> 
> Best,
> Sergey
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list