I'd like to perform an exponentially weighted moving average (with parameterization defined here) on a vector in R. Is there a better implementation than my first attempt below?
My first attempt was:
ewma <- function(x, a) {
n <- length(x)
s <- rep(NA,n)
s[1] <- x[1]
if (n > 1) {
for (i in 2:n) {
s[i] <- a * x[i] + (1 - a) * s[i-1]
}
}
return(s)
}
y <- 1:1e7
system.time(s <- ewma(y,0.5))
#user system elapsed
# 2.48 0.00 2.50
In my second attempt, I thought I could do better by vectorizing:
ewma_vectorized <- function(x,a) {
a <- 0.1
n <- length(x)
w <- cumprod(c(1, rep(1-a, n-1)))
x1_contribution <- w * x[1]
w <- a * w
x <- x[-1]
s <- apply(as.array(1:(n-1)), 1, function(i,x,w){sum(w[i:1] * x[1:i])}, x=x, w=w)
s <- x1_contribution + c(0,s)
return(s)
}
system.time(s <- ewma_vectorized(y,0.5))
# I stopped the program after it continued to run for 4min
I guess I shouldn't have been too surprised by the results in my second attempt. It was a pretty ugly attempt at vectorization. But there has to be something like this that improves on my first attempt...right?
UPDATE:
I did find a better implementation here and adapted it as follows:
ewma_vectorized_v2 <- function(x, a) {
s1 <- x[1]
sk <- s1
s <- vapply(x[-1], function(x) sk <<- (1 - a) * x + a * sk, 0)
s <- c(s1, s)
return(s)
}
system.time(s <- ewma_vectorized_v2(y,0.5))
# user system elapsed
# 1.74 0.01 1.76