4

I've been trying for a while now to produce a code that brings me a new vector of the sum of the 25 previous rows for an original vector.

So if we say I have a variable Y with 500 rows and I would like a running sum, in a new vector, which contains the sum of rows [1:25] then [2:26] for the length of Y, such as this:

y<-1:500
runsum<-function(x){
   cumsum(x)-cumsum(x[26:length(x)])
}

new<-runsum(y)

I've tried using some different functions here and then even using the apply functions on top but none seem to produce the right answers....

Would anyone be able to help? I realise it's probably very easy for many of the community here but any help would be appreciated

Thanks

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Ash
  • 73
  • 2
  • 6
  • [possible duplicate](http://stackoverflow.com/questions/10930810/cumulative-sum-for-n-rows) – Roland Jun 14 '12 at 14:13

3 Answers3

3

This function calculates the sum of the 24 preceding values and the actual value:

 movsum <- function(x,n=25){filter(x,rep(1,n), sides=1)}

It is easy to adapt to sum only preceding values, if this is what you really want.

Roland
  • 127,288
  • 10
  • 191
  • 288
3

In addition to Roland's answer you could use the zoo library

library ( zoo )
y <- 1:500
rollapply ( zoo ( y ), 25, sum )

HTH

Jase_
  • 1,186
  • 9
  • 12
1

I like Roland's answer better as it relies on a time series function and will probably be pretty quick. Since you mentioned you started going down the path of using apply() and friends, here's one approach to do that:

y<-1:500
#How many to sum at a time?
n <- 25
#Create a matrix of the appropriate start and end points
mat <- cbind(start = head(y, -(n-1)), end = tail(y, -(n-1)))
#Check output
rbind(head(mat,3), tail(mat,3))
#-----
       start end
           1  25
           2  26
           3  27
[474,]   474 498
[475,]   475 499
[476,]   476 500

#add together
apply(mat, 1, function(x) sum(y[x[1]]:y[x[2]]))

#Is it the same as Roland's answer after removing the NA values it returns?
all.equal(apply(mat, 1, function(x) sum(y[x[1]]:y[x[2]])),
          movsum(y)[-c(1:n-1)])
#-----
[1] TRUE
Chase
  • 67,710
  • 18
  • 144
  • 161
  • Thanks - it helpful to see the apply function being used in a manner related to my work - I'll try this way out too so I at least know how it all works! – Ash Jun 15 '12 at 13:29