Why manual autocorrelation does not match acf() results?

0 r autocorrelation

I'm trying to understand acf and pacf. But do not understand why acf() results do not match simple cor() with lag1

I have simulated a time series

set.seed(100)
ar_sim <- arima.sim(list(order = c(1,0,0), ar = 0.4), n = 100)

ar_sim_t <- ar_sim[1:99]
ar_sim_t1 <- ar_sim[2:100]

cor(ar_sim_t, ar_sim_t1)   ## 0.1438489
acf(ar_sim)[[1]][2]        ## 0.1432205
Run Code Online (Sandbox Code Playgroud)

Could you please explain why the first lag correlation in acf() does not exactly match the manual cor() between the series and lag1?

Rui*_*das 5

下面是估计具有已知均值和方差离散过程的自相关的正确方法。参见例如Wikipedia

n <- length(ar_sim)
l <- 1
mu <- mean(ar_sim)
s <- sd(ar_sim)

sum((ar_sim_t - mu)*(ar_sim_t1 - mu))/((n - l)*s^2)
#[1] 0.1432205
Run Code Online (Sandbox Code Playgroud)

此值不是identical由内置计算得出的值,stats::acf但非常接近它。

a.stats <- acf(ar_sim)[[1]][2]
a.manual <- sum((ar_sim_t - mu)*(ar_sim_t1 - mu))/((n - l)*sd(ar_sim)^2)

all.equal(a.stats, a.manual)  # TRUE
identical(a.stats, a.manual)  # FALSE

a.stats - a.manual
#[1] 1.110223e-16
Run Code Online (Sandbox Code Playgroud)