## investigate the autorcorrelation in the residuals of a fitted model
## simulate data
set.seed(123)
phi <- c(0.4, 0.7, -0.3)
y <- 0
y[2] <- phi[1] * y[1] + rnorm(1)
y[3] <- phi[1] * y[2] + phi[2] * y[1] + rnorm(1)
for (i in 4:300) y[i] <- sum(phi * y[(i-1):(i-3)]) + rnorm(1)
## fit the model
fit1 <- brm(y ~ 1)
summary(fit1)
## investigate the residuals (autocorrelation clearly visible)
macf(residuals(fit1, summary = FALSE), lag.max = 10)
## fit the model again with autoregressive coefficients
fit2 <- brm(y ~ 1, autocor = cor_ar(p = 3))
summary(fit2)
## investigate the residuals again (autocorrelation is gone)
macf(residuals(fit2, summary = FALSE), lag.max = 10)
Run the code above in your browser using DataLab