0

I'd like to calculate the mean deviation '1/n[sum(Xi-mu)]' with rolling window. The 'mu' is rolling average. And Xi is rolling observation, too. Here is my sample code with window size n=10:

library(TTR)
dt<-rnorm(10000)
avg<-runMean(dt,n=10,cumulative=F)
df<-data.frame(dt,avg)

ls<-lapply(10:nrow(df),function(.){
    dev<-(df[(.-10+1):.,'dt']-df[.,'avg'])
    sk=mean(dev)
})

(p<-unlist(ls))

It seems the lapply is not an efficient way. Not sure what is alternative solution. Thank you anyone for any suggestion.

YYY
  • 605
  • 3
  • 8
  • 16

1 Answers1

2

Do you mean something like this (although the differences cancel out as simply explained here)?

library(zoo)
dt <- rnorm(1000)
rollapply(dt, 10, function(x) mean(x - mean(x)))
DatamineR
  • 10,428
  • 3
  • 25
  • 45