[R] Generalized cumsum?
David Winsemius
dwinsemius at comcast.net
Thu Sep 17 03:21:28 CEST 2009
On Sep 16, 2009, at 9:04 PM, OKB (not okblacke) wrote:
> 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?
cumapply <- function (FUN, X)
{ FUN <- match.fun(FUN)
answer <- sapply(1:length(X), function(x) { FUN(X[1:x])} )
return(answer)}
cumapply(mean, c(1,2,3,4))
### [1] 1.0 1.5 2.0 2.5
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list