ewma <- function(x, lambda=0.94){ rs <- c() for(idx in 1:length(x)){ if (idx == 1){ rs <- c(x[idx]) } else { rs <- c(rs, lambda * x[idx] + (1-lambda)*rs[idx-1]) } } return(data.frame(idx, x, ewma=rs)) } x <- c(100, 150, 120, 150) ewma(x, lambda = 0.3)
> ewma(x, lambda = 0.3) idx x ewma 1 4 100 100.00 2 4 150 115.00 3 4 120 116.50 4 4 150 126.55