吉林小王子 发表于 2012-2-19 15:55 
不用啊,你读入数据,然后稍微修改一下,从里面取出你想要的部分不就行了嘛,
至于坐标问题,在前面已经恢 ...
吉林小王子你好:我的命令出了些问题,我用lm1就可以predict,用lm2就不行了:
# ---- Linear Trend Model -----
y <- read.csv(file="data.csv",head=TRUE,sep=",")#input the data with head
print(y)
tsy <- ts(y, start=1992, frequency=1)
plot.ts(tsy,type="l",col="blue",ylab="gdp per capita",xlab="year") #plot the time series
is.ts(tsy)# test whether it is time series
t=1992:2007
lm1<-lm(tsy~t,na.action=NULL)# linear trend model
#-- the na.action statement is to retain time series attributes
summary(lm1)
model.matrix(lm1) #You can view the model matrix (with the dummy variables) this way:
yhat=fitted(lm1) #fitted value of the model
e=residuals(lm1) #forecast error of the model
tsyhat<-ts(fitted(lm1),start=1992, frequency=1)# make the yhat time series
tse<-ts(e,start=1992,frequency=1) # make the forecast error time series
ts.plot(tsy,type="p",lwd=2,col="red",ylab="GDP per capita",xlab="Year")
lines(tsyhat)
ts.plot(tse,type="l",lwd=2,col="blue",ylab="Forecast error",xlab="Year")
abline(h=0,col="red")
# ---- Out of sample prediction, use 1992-2005 data as in sample, and 2006-2007 as out of sample -----
##do the out of sample prediction
r=data.frame(y)# change y into data frame
yinsample<-r[1:14,] #get the data of 1992 to 2005
print(yinsample)
tsyinsample<-ts(yinsample)
t3=1992:2005
lm2<-lm(tsyinsample~t3,na.action=NULL)# the in sample linear trend model
summary(lm2)
forecast<-predict(lm2,data.frame(t=2006:2007),se.fit = TRUE,interval ='prediction')
##但是这里用lm1就可以,好困惑啊,为什么呢???print(forecast)
tsy <- ts(y, start=1992, frequency=1)
t=2006:2007
c=data.frame(forecast[1])
y1=c(c$fit.lwr, c$fit.upr, c$fit.fit)
t1=rep(t,3)
plot(t1,y1,type='p',)
plot(t,c[[1]],type="l",lty=1,lwd=4,xlim=c(1992,2007),ylim=c(500,3000),axes=F,xlab="time",ylab="GDP per capita",main="Out of sample prediction of linear trend model")
axis(1,seq(1992,2007,by=1),seq(1992,2007,by=1))
axis(2)
lines(t,c[[2]],col='red',type='l')
lines(t,c[[3]],col='red',type='l')
text(2006,2250,'upper',col='red')
text(2006.5,1950,'fit',col='black')
text(2006, 1500,'lower',col='red')
text(2004, 2600,'Out of sample prediction',col='black')
text(2004, 2470,'for 2006 and 2007(95% internal)',col='black')
text(1998, 1400,'In sample ture value',col='black')
t1=1992:2007
lines(t1,tsy,type="l")
lines(tsyhat)