Session Ready
Exercise

Simulate AR(p) model

Auto-regressive (AR) models are a type of linear regression for time series where the predicted values depend upon the values at previous time points. Due to this dependence on previous time points, the model must be calculated one time point after another. That means using a for loop, so C++ comes in handy!

Here's the algorithm in R:

ar1 <- function(n, constant, phi, eps) {
  p <- length(phi)
  x <- numeric(n)
  for(i in seq(p + 1, n)) {
    value <- rnorm(1, constant, eps)
    for(j in seq_len(p)) {
      value <- value + phi[j] * x[i - j]
    }
    x[i] <- value
  }
  x
}

n is the number of simulated observations, c is a constant, phi is a numeric vector of autocorrelation coefficients, and eps is the standard deviation of the noise. Complete the definition of ar2(), a C++ translation of ar1().

Instructions
100 XP
  • Generate a normally distributed random number with mean c and standard deviation eps, using Rcpp's R API.
  • Make the inner for loop iterate from 0 to p.
  • Inside the inner loop, increase value by the jth element of phi times the "i minus j minus 1"th element of x.