rtime-seriesautoregressive-models

Auto-Regression (2) in R


I need help generating an AR(2) model in R and I am new to the software.

I have the following AR(2) process:

y[t] = phi_1 * y[t-1] + phi_2 * y[t-2] + e[t] where e[t] ~ N(0,2)

How can I generate a series of y[t]?

Thanks for the help, much appreciated!


Solution

  • You could do:

    set.seed(123)
    n <- 200
    phi_1 <- 0.9
    phi_2 <- 0.7
    e <- rnorm(n, 0, 2)
    y <- vector("numeric", n)
    y[1:2] <- c(0, 1)
    for (t in 3:n) {
      y[t] <- phi_1 * y[t - 1] + phi_2 * y[t - 2] + e[t]
    }
    
    plot(seq(n), y, type = "l")