On Sep 16, 2009, at 5:00 PM, OKB (not okblacke) wrote:
Is there anything like cumsum and cumprod but which allows you to
apply an arbitrary function instead of sum and product? In other
words,
I want a function cumfunc(x, f) that returns a vector, so that for
all n
up to the length of x
cumapply(x,f)[n] = f(x[1:n])
?Reduce
Slightly modified from the help page:
> add <- function(x) Reduce("+", x, accumulate=TRUE)
> add(list(1, 2, 3))
[1] 1 3 6
> cummult <- function(x) Reduce("*", x, accumulate=TRUE)
> cummult(list(1, 2, 3))
[1] 1 2 6
This would give cumsum and cumprod as special cases when f=sum or
f=prod.
I could write such a function, but I can't see a way to do it
without a loop, so I'm wondering if such a function exists that may be
speedier.
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
______________________________________________
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.