Wietze
Wietze

Reputation: 109

For loop for time series data

Suppose I have the following simple formula

y[t] = alpha * y[t-1] + beta * y[t-2]

Where y[t-1] and y[t-2] are known observations. Now the next observation at time t+1 can be written as

y[t+1] = alpha * y[t] + beta * y[t-1]

Using previous information of y[t] yields

y[t+1] = alpha * (alpha * y[t-1] + beta * y[t-2]) + beta * y[t-1]

Simplifying

y[t+1] = alpha^2 * y[t-1] + alpha * beta * y[t-2] + beta * y[t-1]

The next observation

y[t+2] = alpha^2 * y[t] + alpha * beta * y[t-1] + beta * y[t]

Where again y[t] can be inserted.

Now my question is how do I write a for loop such that I can construct y at time t+h where h is an integer value.

Upvotes: 0

Views: 45

Answers (1)

jpdugo17
jpdugo17

Reputation: 7106

Something like this?

y = c(1, 2, rep(0, 49)) 
alpha <- .4
beta <- .9

for (t in 3:length(y)) {
    y[t] <-  alpha * y[t-1] + beta * y[t-2]
}

nms <- paste0('y[', as.character(seq(-2, 48, 1)), ']') 

`names<-`(y, nms)
#>       y[-2]       y[-1]        y[0]        y[1]        y[2]        y[3] 
#>    1.000000    2.000000    1.700000    2.480000    2.522000    3.240800 
#>        y[4]        y[5]        y[6]        y[7]        y[8]        y[9] 
#>    3.566120    4.343168    4.946775    5.887561    6.807122    8.021654 
#>       y[10]       y[11]       y[12]       y[13]       y[14]       y[15] 
#>    9.335072   10.953517   12.782971   14.971354   17.493216   20.471505 
#>       y[16]       y[17]       y[18]       y[19]       y[20]       y[21] 
#>   23.932496   27.997353   32.738188   38.292893   44.781526   52.376214 
#>       y[22]       y[23]       y[24]       y[25]       y[26]       y[27] 
#>   61.253859   71.640136   83.784528   97.989934  114.602048  134.031760 
#>       y[28]       y[29]       y[30]       y[31]       y[32]       y[33] 
#>  156.754547  183.330403  214.411254  250.761864  293.274874  342.995627 
#>       y[34]       y[35]       y[36]       y[37]       y[38]       y[39] 
#>  401.145637  469.154319  548.692801  641.716008  750.509925  877.748377 
#>       y[40]       y[41]       y[42]       y[43]       y[44]       y[45] 
#> 1026.558283 1200.596853 1404.141196 1642.193646 1920.604534 2246.216095 
#>       y[46]       y[47]       y[48] 
#> 2627.030519 3072.406693 3593.290144

Created on 2021-06-12 by the reprex package (v2.0.0)

Upvotes: 1

Related Questions