The goal of this exercise is to familiarize you further with the simulation, modeling, and statistical analysis of time series. In addition to your report—which should contain answers to the questions and the relevant graphs—please remember to submit the script containing all the commands used, as well as a saved copy of your workspace: DM.RData.
##### random parameters
a=rnorm(1,10,2)
b=rnorm(1,12400,100)
tau=sample(6:24,1)
##### simulations
time=seq(2005,2014+11/12,1/12)
Te=a*time^2-a*4013*time+(a*4014010+b)
S=rep_len(180*sin((0:(tau-1))*2*pi/tau),120)
E=rnorm(120,0,30)
X=ts(Te+S+E,start=c(2005,1),freq=12)
##### Saving the workspace
save(list=c('time','T','S','E','X'),file="DM.RData")
The last command saves the variables you have just created. This is essential because they are randomly generated and therefore must not be regenerated every time you restart R (otherwise, you would have to start all over again).
plot(X)
# period
tau
## [1] 12
# additive model
# non-linear trend (hyperbolic)
# moving average of order tau
if (tau%%2==0){moymob=filter(X,c(.5,rep(1,tau-1),.5)/tau)}
if (tau%%2==1){moymob=filter(X,rep(1,tau)/tau)}
plot(X)
lines(moymob,col="red")
lines(time,Te,col='blue')
# Number of complete cycles
N=floor(120/tau)
Z=X-moymob
p=tau
Sais=rep(NA,tau)
for (i in 1:tau)
{
if (i<=floor(tau/2)) {Sais[i]=mean(Z[i+tau*(1:(N-1))])}
else {Sais[i]=mean(Z[i+tau*(0:(N-2))])}
}
plot(S[1:tau])
lines(Sais,col='red')
dsX=X-rep_len(Sais,120)
plot(time,dsX,type='p')
# non-linear scatter plot, variable transformation necessary
zt = (time-2005)^2-3*(time-2005) Plot the scatter plot of
dsX against zt. Comment on the
result.zt = (time-2005)^2-3*(time-2005)
plot(zt,dsX,type='p')
# linear scatter plot, positive slope
cor(zt,dsX)
## [1] 0.9936029
# confirms strong linear relationship and positive slope
##
## Call:
## lm(formula = dsX ~ zt)
##
## Residuals:
## Min 1Q Median 3Q Max
## -50.712 -21.615 -0.527 20.992 76.073
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.323e+05 3.487e+00 -37935.89 <2e-16 ***
## zt 1.193e+01 1.249e-01 95.57 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 29.15 on 118 degrees of freedom
## Multiple R-squared: 0.9872, Adjusted R-squared: 0.9871
## F-statistic: 9134 on 1 and 118 DF, p-value: < 2.2e-16
## dsX= 11.93423 zt+ -132273.4
## R2= 0.9872466
## very good model quality
## 1 2 3 4 5 6 7 8
## -108135.9 -108069.1 -108044.0 -108067.1 -108132.0 -108221.0 -108310.0 -108374.9
## 9 10 11 12
## -108398.0 -108372.9 -108306.0 -108215.0