2013-03-23 92 views
1

您好计算自相关我试图计算与滞后的自相关U,U = 1 ... 9与滞后ü中的R

我期望9X1自相关函数。但是,当我尝试使用此代码时,它总是给我10x1自相关函数,第一项= 1。我不知道如何继续。

# initialize a vector to store autocovariance 
maxlag <- 9 
varstore <- rep(NA,maxlag) 
# Calculate Variance 
varstore[1] <- sd(as.vector(sample1),na.rm=T)^2 

# Estimate autocovariances for all residuals 
for (lag in 1:maxlag) 
    varstore[lag+1] <- mean(sample1[,1:(10-lag)] * 
         sample1[,(lag+1):10],na.rm=T) 
print(round(varstore,3)) 
# calculate autocorrelations 
corrstore <- varstore/varstore[1] 
print(corrstore) 

而这就是我得到:

[1] 1.0000000 0.6578243 0.5670389 0.5292314 0.5090411 0.4743944 0.4841038 0.4756297 
[9] 0.4275208 0.4048436 
+1

什么是'sample1'?你也应该把空间转换成我的编码(就像我现在编辑的那样)。 – Arun 2013-03-23 10:20:26

回答

3

你得到,因为回收的长度为10的矢量。

lag =maxlog(您for循环的最后一步)

varstore[lag+1] 

将创建NA一个新条目。为了清楚地看到这一点,试试这个,例如:

v <- NA  ## a vector of length 1 
v[10] <- 2 
v 
[1] NA NA NA NA NA NA NA NA NA 2 ## you get a vector of legnth 10!! 

That'said,你为什么要长9的载体?为什么不使用acf功能?这里acf功能的输出:

length(acf(1:10)$lag) 
[1] 10