using "rollapply" to calculate a moving sum or running sum?
On Thu, Jun 27, 2013 at 3:00 PM, Anika Masters <anika.masters at gmail.com> wrote:
#using "rollapply" to calculate a moving sum or running sum?
#I am tryign to use rollapply to calcualte a moving sum? #I tried
rollapply and get the error message
#"Error in seq.default(start.at, NROW(data), by = by) :
# wrong sign in 'by' argument"
#example:
mymatrix <- ( matrix(data=1:100, nrow=5, ncol=20) )
mymatrix_cumsum <- ( matrix(data=NA, nrow=5, ncol=20) )
w=12
for(i in 1: (ncol(mymatrix)-w+1) ) {
mymatrix_cumsum[ , i] <- apply(X=mymatrix[, i:(i+w-1)] , MARGIN=1,
FUN=sum, na.rm=T)
}
#How might I use the "rollapply" function instead?
rollapply(mymatrix, 12, sum)
rollapply(data = mymatrix, width = 12, FUN=sum, by.column =T, fill =
NA, partial = FALSE, align = "left" )
rollapply works column at a time (not row at a time) so try this: t( rollapply( t(mymatrix), 12, sum ) ) -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com