我在下面包含了一个示例,以展示如何计算 Bartlett 近似值并将它们添加到自相关函数图中的一种方法。
在示例中,我是手动完成的,而不是依赖特定的包,因此代码比可能需要的要长。我不声称代码是有效的,但它确实得到了正确的结果。
我的示例中的结果可以与图 C1.2 的准确性进行比较。在Pankratz (1983)的案例 1 中,它使用了我使用过的相同数据集。如果您没有这本书,请不要担心,因为案例 1 的内容可以免费下载。
请注意,稍作修改,下面的代码可用于绘制 pacf 上的标准误差,Scortchi 已正确指出应该等于。n−1/2
# Import data from the web
inventories <- scan("http://robjhyndman.com/tsdldata/books/pankratz.dat", skip=5, nlines=5, sep="")
# Calculate sample size and mean
n <- length(inventories)
mean.inventories <- sum(inventories)/n
# Express the data in deviations from the mean
z.bar <- rep(mean.inventories,n)
deviations <- inventories - z.bar
# Calculate the sum of squared deviations from the mean
squaredDeviations <- deviations^2
sumOfSquaredDeviations <-sum(squaredDeviations)
# Create empty vector to store autocorrelation coefficients
r <- c()
# Use a for loop to fill the vector with the coefficients
for (k in 1:n) {
ends <- n - k
starts <- 1 + k
r[k] <- sum(deviations[1:(ends)]*deviations[(starts):(n)])/sumOfSquaredDeviations
}
# Create empty vector to store Bartlett's standard errors
bart.error <- c()
# Use a for loop to fill the vector with the standard errors
for (k in 1:n) {
ends <- k-1
bart.error[k] <- ((1 + sum((2*r[0:(ends)]^2)))^0.5)*(n^-0.5)
}
# Plot the autocorrelation function
plot(r[1:(n/4)],
type="h",
main="Autocorrelation Function",
xlab="Lag",
ylab="ACF",
ylim=c(-1,1),
las=1)
abline(h=0)
# Add Bartlett's standard errors to the plot
lines(2*bart.error[1:(n/4)])
lines(2*-bart.error[1:(n/4)])
运行代码后,您应该看到以下图表:
