#Packages
library(car)
library(astsa)
library(orcutt)
library(astsa)#To use lag1.plot()
library(car)
library(orcutt)
#Data Setup
Sale=read.table(file="E:\\R Code files\\R Data Sets\\Autocorrelation.csv",header=T,sep=",")
attach(Sale)
names(Sale)
## [1] "Sales" "Adcost"
Sale
## Sales Adcost
## 1 3.63 0.97
## 2 4.20 0.95
## 3 3.33 0.99
## 4 4.54 0.91
## 5 2.89 0.98
## 6 4.87 0.90
## 7 4.90 0.89
## 8 5.29 0.86
## 9 6.18 0.85
## 10 7.20 0.82
## 11 7.25 0.79
## 12 6.09 0.83
## 13 6.80 0.81
## 14 8.65 0.77
## 15 8.43 0.76
## 16 8.29 0.80
## 17 7.18 0.83
## 18 7.90 0.79
## 19 8.45 0.76
## 20 8.23 0.78
#Understanding Autocorrelation
Model=lm(Sales~Adcost,data=Sale)
plot(Model)




e=Model$residuals
e=ts(e)#Telling R to residuala are in time order.
e
## Time Series:
## Start = 1
## End = 20
## Frequency = 1
## 1 2 3 4 5
## 0.2811931818 0.3653977273 0.4669886364 -0.2661931818 -0.2159090909
## 6 7 8 9 10
## -0.1790909091 -0.3919886364 -0.7306818182 -0.0835795455 0.2077272727
## 11 12 13 14 15
## -0.4709659091 -0.6593750000 -0.4351704545 0.4432386364 -0.0196590909
## 16 17 18 19 20
## 0.8119318182 0.4306250000 0.1790340909 0.0003409091 0.2661363636
plot(e)

Auto=acf(e,xlim=c(0,10))#Autocorrelatiofunction

Auto$acf
## , , 1
##
## [,1]
## [1,] 1.000000000
## [2,] 0.409436792
## [3,] 0.134685708
## [4,] 0.006113339
## [5,] 0.073428259
## [6,] -0.207687821
## [7,] -0.132333776
## [8,] -0.039741445
## [9,] -0.222908700
## [10,] -0.353989966
## [11,] -0.326486113
## [12,] -0.144274745
## [13,] -0.152755262
## [14,] 0.072227517
lag1.plot(e,1)

#Durbin Watson test for autocorrelation
DWT=durbinWatsonTest(lm(Sales~Adcost))#Two sides
DWT
## lag Autocorrelation D-W Statistic p-value
## 1 0.4094368 1.135816 0.03
## Alternative hypothesis: rho != 0
PositiveDWT=durbinWatsonTest(lm(Sales~Adcost,data=Sale),alternative="positive")
PositiveDWT
## lag Autocorrelation D-W Statistic p-value
## 1 0.4094368 1.135816 0.013
## Alternative hypothesis: rho > 0
NegativeDWT=durbinWatsonTest(lm(Sales~Adcost,data=Sale),alternative="negative")
NegativeDWT
## lag Autocorrelation D-W Statistic p-value
## 1 0.4094368 1.135816 0.99
## Alternative hypothesis: rho < 0
#Cochrane-Orcutt Method
Model=lm(Sales~Adcost,data=Sale)
CO=cochrane.orcutt(Model)
CO# it calculates the original beta values,not transformed beta values(b/(1-rho))
## Cochrane-orcutt estimation for first order autocorrelation
##
## Call:
## lm(formula = Sales ~ Adcost, data = Sale)
##
## number of interaction: 8
## rho 0.425232
##
## Durbin-Watson statistic
## (original): 1.13582 , p-value: 9.813e-03
## (transformed): 1.95804 , p-value: 4.151e-01
##
## coefficients:
## (Intercept) Adcost
## 26.72209 -24.08413