[R] partial cumsum

William Dunlap wdunlap at tibco.com
Wed Nov 11 18:33:58 CET 2009


> -----Original Message-----
> From: smu [mailto:ml at z107.de] 
> Sent: Wednesday, November 11, 2009 9:26 AM
> To: William Dunlap
> Cc: r-help at r-project.org
> Subject: Re: [R] partial cumsum
> 
> On Wed, Nov 11, 2009 at 08:53:50AM -0800, William Dunlap wrote:
> > 
> > Perhaps
> >    > ave(x, rev(cumsum(rev(is.na(x)))), FUN=cumsum)
> >     [1]  1  3  6 NA  5 11 18 26 35 45
> > 
> 
> it takes some time to understand how it works, but it's perfect.

Note that the 2nd argument assigns a group number
based on the number of NA's prior to the current
position in the vector.  The odd repeated calls to
rev() are there to put the NA's at the ends of the
groups, instead of at the beginnings:
   > x <- c(1, 2, 3, NA, 5, 6, 7, 8, 9, 10)
   > rev(cumsum(rev(is.na(x))))
    [1] 1 1 1 1 0 0 0 0 0 0
A more natural way to do this is
   > cumsum(is.na(c(NA,x[-length(x)])))
    [1] 1 1 1 1 2 2 2 2 2 2

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> 
> thank you,
>  stefan
> 




More information about the R-help mailing list