[R-SIG-Finance] Running sum by subset time series

Gabor Grothendieck ggrothendieck at gmail.com
Thu Sep 9 04:32:25 CEST 2010


On Wed, Sep 8, 2010 at 9:12 PM, Wilfred Daye <wdaye01 at gmail.com> wrote:
> Hi, I have the following zoo object, which has an index of {0,4}.  The
> values are 1 to 20 each day.  In a sense, I have 4 subsets of 5 vectors
> index by time.  I want to do a running sum for each subset of data in this
> time series as show below in results column.  If I use any of the
> rolling/running functions, I get running sum of the whole time series
> without subset blocks.  Please advise the best way to approach this
> problem.  Thank you, Wilfred
>
> Date    index    [,1]    result
> 9/8/2010    0    1    1
> 9/9/2010    1    2    3
> 9/10/2010    2    3    6
> 9/11/2010    3    4    10
> 9/12/2010    4    5    15
> 9/13/2010    0    6    6
> 9/14/2010    1    7    13
> 9/15/2010    2    8    21
> 9/16/2010    3    9    30
> 9/17/2010    4    10    40
> 9/18/2010    0    11    11
> 9/19/2010    1    12    23
> 9/20/2010    2    13    36
> 9/21/2010    3    14    50
> 9/22/2010    4    15    65
> 9/23/2010    0    16    16
> 9/24/2010    1    17    33
> 9/25/2010    2    18    51
> 9/26/2010    3    19    70
> 9/27/2010    4    20    90
>

If z is your zoo object and z[,2] is the column of interest then try:

nr <- nrow(z)
ave(z[,2], gl(nr, 5, nr), FUN = cumsum)

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-SIG-Finance mailing list