YYY
YYY

Reputation: 625

Is there an efficient way to calculate rolling deviation from mean?

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.

Upvotes: 0

Views: 127

Answers (1)

DatamineR
DatamineR

Reputation: 9618

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)))

Upvotes: 2

Related Questions