Skip to content

Partial sum of a vector

8 messages · Jorge Ivan Velez, jim holtman, Mohammad Sabr +2 more

#
?filter
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
Time Series:
Start = 1
End = 20
Frequency = 1
 [1] NA 10 14 18 22 26 30 34 38 42 46 50 54 58 62 66 70 74 NA NA
On Sun, Mar 1, 2009 at 9:29 PM, Mohammad Sabr <mohammad_sabr at yahoo.com> wrote:

  
    
#
perhaps this?

M <- dim(data_m)[2]

for(j in 1:M){
    for (i in 4:T) {
        data_q[i-3,j]=sum(data_m[(i-3):i,j])
    }
}

of course, you can vectorize this and speed it up significantly, but
there is something evil about premature optimization.
On Mar 2, 1:29?pm, Mohammad Sabr <mohammad_s... at yahoo.com> wrote:
#
Per the help page rollapply needs to be given a zoo or ts object, so  
you just coerce the matrix to zoo:

 > data_m <- matrix(1:20, ncol=2)
 > data_q <-matrix(,nrow=7,ncol=2)
# then you can vectorize the process
 > data_q[,] <-rollapply(as.zoo(data_m[,]),4,FUN=sum)
 > data_q
      [,1] [,2]
[1,]   10   50
[2,]   14   54
[3,]   18   58
[4,]   22   62
[5,]   26   66
[6,]   30   70
[7,]   34   74