【数学分析入门】R语言一元以及多元线性回归及诊断

文章目录

    • 1 一元线性回归
    • 2 多元线性回归
      • 当各变量独立时
      • 当各变量不独立时
      • 当变量太多,组合太多时
        • AIC比较法
        • 徒步回归法(Backward stepwise selection)
        • 全回归法
    • 3 回归诊断

1 一元线性回归

fit <- lm(weight~height,data=women)            
summary.lm(fit)
fit
coefficients(fit)
confint(fit)
confint(fit,level=0.5)
fitted(fit)
residuals(fit)
women1<-women
predict(fit,women1)
plot(fit)
plot(women$height,women$weight)
abline(fit)
fit2<-lm(weight~height+I(height^2),data=women)
summary(fit2)
plot(women$height,women$weight)
lines(women$height,fitted(fit2),col='red')

2 多元线性回归

当各变量独立时

states <- as.data.frame(state.x771,c("Murder","Population"
Lutcoracy" "Incoma" "ErOSO)]) 
fit <- lm(Murder ~ Population + Illiteracy + Income + Frost, data=states) summary(fit) 
##看各个变量的系数
coef(fit)
gqPlot(fit, labels=row.names(states), id.method="identify",
simulate-TRUE, main-"o-o plot")

当各变量不独立时

fit <- lm(mpg . hp + wt + hp:wt,data=mtcars) 
summary(fit)

当变量太多,组合太多时

AIC比较法

rit1 <1m(Murder Population+ Illiteracyt Income+ Frost,data states) 
fit2 <-im(Murder Population+ Illiteracy,data = states) 
AIC(fit1,fit2)

徒步回归法(Backward stepwise selection)

library(MASS)
states <-as.data.frame(state.x77[,c(Murder","population",
"Illiteracy","Income","Frost")])
fit <- lm(Murder - Population + Illiteracy + Income + frost,
data-states)
stepAIc(fit, direction="backward")

全回归法

library(leaps)
states <-as.data.frame(state.x77l,c("Murder", "population",
"Illiteracy""Income""Frost")])
leaps <-regsubsets (Murder ~ Population + Illiteracy + Income +
Frost,data=states,nbest=4)
plot(lcaps, scale-"adjr2")

3 回归诊断

opar <- par (no.readonly=TRUE)
fit <- lm(weight ~ height, data=women) 
par(mfrow=c(2,2)) 
plot(fit) 
par(opar)
fit2 <- lm(weight ~ height + I(height^2), data=women) 
opar <- par(no.readonly=TRUE) 
par(mfrow=c(2,2)) 
plot(fit2) 
par(opar)

第一幅图是残差与拟合的图
QQ图用来描述正态分布性,如果正态分布,那么呈直线分布

你可能感兴趣的:(数据分析,r语言)