In stats::arima
, the first residual of an AR(1) model is obtained as a byproduct of the Kalman filter. Example for an AR(1) model:
# generate 120 observations from an AR(1) model
set.seed(123)
y <- arima.sim(n = 120, model = list(ar=0.6))
# fit the model
fit <- arima(y, order = c(1,0,0), include.mean = FALSE)
# get the state space representaton of the fitted model and
# run the Kalman filter
ss <- makeARIMA(phi = coef(fit), theta = numeric(0), Delta = numeric(0))
kf <- KalmanRun(y = y, mod = ss)
# residuals
head(as.vector(residuals(fit)))
# [1] 0.5017314 -0.5510861 1.7855220 0.5106597 -1.9551303 0.6932320
head(kf$resid)
# [1] 0.5017314 -0.5510861 1.7855220 0.5106597 -1.9551303 0.6932320
all.equal(as.vector(residuals(fit)), kf$resid)
# [1] TRUE
For some introduction on how the Kalman filter operates on ARMA models you may see, for example, this postthis post.