Skip to content

time-varying recursive filter - vectorized

1 message · Felix Andrews

#
A question about vectorized operations (avoiding loops, for speed)...

I need to run a simple recursive (autoregressive) filter with a
time-varying coefficient. It is just a one-step recursive filter, so
it would be an exponential decay if the filter was constant.

I just want to do this, where 'x' is the data and 'w' is the weight to
apply to the previous time step:

x <- c(1, 1, 0, 2, 0, 0)
w <- c(NA, 0.1, 0.5, 0.4, 0.3, 0.2)
y <- x
for (i in seq_along(x)[-1]) y[i] <- y[i] + w[i] * y[i-1]
print(y)
[1] 1.0000 1.1000 0.5500 2.2200 0.6660 0.1332

But, since loops are slow, I would like a vectorized method, like
filter(, method="recursive").

Any ideas?