1.GDP1.R
#先做这个
GDP1 <- read.table("GDP.txt",header=TRUE)
GDP1
reg1 <- lm(y~x1+x2+x3+x4+x6+x7+x8, data=GDP1)
summary(reg1)
reg1.Stepwise <-step(reg1,direction="both")
summary(reg1.Stepwise)
##说明GDP和x7,x8有关
2.GDP.R
#接GDP1.R
GDP <- read.table("GDP.txt",header=TRUE)
GDP
#线性回归
Reg <- lm(y~x7+x8, data=GDP)
summary(Reg)
plot(Reg)
#coefficients(Reg)
#fitted(Reg)
rstudent(Reg) #rstudent()函数:检测异常值与强影响点,绝对值大于3为异常值
#模型预测1
lm.pred<-predict(Reg, GDP[,c(8,9)], interval="prediction", level=0.95)
lm.pred
(dataplot=data.frame(lm.pred,GDP[,c(1,9)]))
plot(dataplot[,c(5,4)],col=2) #真实值点
points(dataplot[,c(5,1)],pch=20,col=4) #预测值点
lines(dataplot[,c(5,2)]) #下95%置信曲线
lines(dataplot[,c(5,3)]) #上95%置信曲线
#模型预测2
lm.pred<-predict(Reg, GDP[,c(8,9)], interval="prediction", level=0.95)
lm.pred
(dataplot=data.frame(lm.pred,GDP[,c(1,8)]))
plot(dataplot[,c(5,4)],col=2) #真实值点
points(dataplot[,c(5,1)],pch=20,col=4) #预测值点
lines(dataplot[,c(5,2)]) #下95%置信曲线
lines(dataplot[,c(5,3)]) #上95%置信曲线
#拟合值和真实值非常接近,拟合效果非常好
3.GDP2.R
GDP2 <- read.table("GDP.txt",header=TRUE)
GDP2
#线性回归
Reg2<-lm(y~x1+x2+x3+x4+x5+x6+x7+x8, data=GDP2)
summary(Reg2)
Reg2.Stepwise <-step(Reg2,direction="both")
#逐步回归step函数在R基础包stats中
summary(Reg2.Stepwise)
#从逐步回归结果看,X6不够显著,仅利用X5,x8进行回归
Reg2.Stepwise.Modified <- lm(y~x5+x8, data=GDP2)
summary(Reg2.Stepwise.Modified)
coefficients(Reg2.Stepwise.Modified)
par(mfrow=c(2,2))
plot(Reg2.Stepwise.Modified)
#####全子集回归#####
#leaps包中的regsubsets()函数实现。
#能通过R平方、调整R平方或 Mallows Cp统计量
#等准则来选择“佳”模型。
library(leaps)
leaps <-
regsubsets(y~x1+x2+x3+x4+x5+x6+x7+x8,
data=GDP2, nbest=8)
plot(leaps, scale="adjr2")
plot(leaps, scale="bic")
全子集1 <- summary(leaps)
(全子集2 <- data.frame(全子集1$outmat,调整R方=全子集1$adjr2))