## 13.2 Linear regression with correlated errors

In our first model, the errors were independent in time. We’re going to modify this to model autocorrelated errors. Autocorrelated errors are widely used in ecology and other fields – for a greater discussion, see Morris and Doak (2002) Quantitative Conservation Biology. To make the errors autocorrelated, we start by defining the error in the first time step, $${e}_{1} = y_{1} - \beta$$. The expectation of $${Y_t}$$ in each time step is then written as $E[{Y_t}] = \beta + \phi e_{t-1}$

In addition to affecting the expectation, the correlation parameter $$\phi$$ also affects the variance of the errors, so that ${ \sigma }^{ 2 }={ \psi }^{ 2 }\left( 1-{ \phi }^{ 2 } \right)$ Like in our first model, we assume that the data follows a normal likelihood (or equivalently that the residuals are normally distributed), $$y_t = E[Y_t] + e_t$$, or $$Y_t \sim N(E[{Y_t}], \sigma)$$. Thus, it is possible to express the subsequent deviations as $${e}_{t} = {y}_{t} - E[{Y_t}]$$, or equivalently as $${e}_{t} = {y}_{t} - \beta -\phi {e}_{t-1}$$.

We can fit this regression with autocorrelated errors by changing the model name to ‘regression_cor’

lm_intercept_cor <- atsar::fit_stan(y = Temp, x = rep(1, length(Temp)),
model_name = "regression_cor", mcmc_list = list(n_mcmc = 1000,
n_burn = 1, n_chain = 1, n_thin = 1))