# [R] time-varying recursive filter - vectorized

Felix Andrews felix at nfrac.org
Thu Jul 12 13:29:16 CEST 2007

```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?

--
Felix Andrews / 安福立
PhD candidate, The Fenner School of Environment and Society
The Australian National University (Building 48A), ACT 0200
Beijing Bag, Locked Bag 40, Kingston ACT 2604
http://www.neurofractal.org/felix/
voice:+86_1051404394 (in China)
mobile:+86_13522529265 (in China)
mobile:+61_410400963 (in Australia)
xmpp:foolish.android at gmail.com
3358 543D AAC6 22C2 D336  80D9 360B 72DD 3E4C F5D8

```