0

I am trying to use loops to make my own stats::filter(method = "recursive") function. Per the documentation:

Applies linear filtering to a univariate time series or to each series separately of a multivariate time series. Note that there is an implied coefficient 1 at lag 0 in the recursive > filter, which gives

y[i] = x[i] + f1*y[i-1] + … + f[p]*y[i-p]

Also, from a previous post here is an example:

> filter(1:5, f1, method="recursive")
[1]  1  3  6 10 15

> y1 <- x[1]                                            
> y2 <- x[2] + f1*y1      
> y3 <- x[3] + f1*y2 
> y4 <- x[4] + f1*y3 
> y5 <- x[5] + f1*y4 
> c(y1,y2,y3,y4,y5)
[1]  1  3  6 10 15

This was my best attempt:

x    <- seq(2, 6)
f1   <- .5
y[1] <- 1

for (i in x) {
  y[i] <- x[i] + f1*y[i-1]
  print(y[i-1])
}

[1] 1
[1] 3.5
[1] 5.75
[1] 7.875
[1] 9.9375

This is what should be the result

> stats::filter(1:5, .5, method = "recursive")
[1] 1.0000 2.5000 4.2500 6.1250 8.0625
Alex
  • 2,603
  • 4
  • 40
  • 73

1 Answers1

0

This solved it:

> x    <- seq(2, 6)
> f1   <- .5
> y[1] <- 1

> for (i in x) {
>   y[i] <- x[i-1] + f1*y[i-1]
>   print(y[i-1])
> }


[1] 1
[1] 2.5
[1] 4.25
[1] 6.125
[1] 8.0625
Alex
  • 2,603
  • 4
  • 40
  • 73