已经进入到读R语言课本的程度了。
# 序
内容来自\(\textit{R in Action}\)第\(202\)页。
# 对比嵌套模型
使用 anova() 函数来比较两个嵌套模型的拟合度。嵌套模型指一个模型的所有变量在另一个模型中都有包含,且它们响应变量也是一样的。
在下面的多元回归模型\(m1\)中,你会发现有些回归系数式不显著的。那么你可以重新做一个不包含\(m1\)中不显著变量的多元回归模型\(m2\),然后对比不包含\(m1\)中不显著变量的多元回归模型\(m2\)是否与\(m1\)在预测上一样好。
states <- as.data.frame(state.x77[,c("Murder", "Population", "Illiteracy", "Income", "Frost")]) //因为state.x77是矩阵,而做回归分析需要用到数据框。所以这里做一个转换,顺便从中只取需要的数据。
m1 <- lm(Murder ~ Population + Illiteracy + Income + Frost, data=states) //可以看到有很多变量
m2 <- lm(Murder ~ Population + Illiteracy, data=states) //可以看到去掉了Income和Frost变量,因为发现在m1中这两个变量的p值不显著
anova(m2, m1) //注意这里的顺序!我们是想看之前包含所有变量的m1是否比去除两个变量的m2好
输出:
Analysis of Variance Table
Model 1: Murder ~ Population + Illiteracy
Model 2: Murder ~ Population + Illiteracy + Income + Frost
Res.Df RSS Df Sum of Sq F Pr(>F)
1 47 289.25
2 45 289.17 2 0.078505 0.0061 0.9939
代码块中输出的\(Model1\)嵌套于\(Model2\), anova() 函数提供了对于回归模型\(m1\)与去掉\(\text{Income}\)和\(\text{Frost}\)变量的回归模型\(m2\)的比较。发现P值等于\(0.9939\)这个测试结果不显著,你就可以得出结论说\(Model2\)的\(\text{Income}\)和\(\text{Frost}\)变量对模型没贡献,原文写作\(\text{they don’t add to the linear prediction}\),进而有正当理由\(\text{ (I’m justified in)}\)把这两个变量从模型中去除掉。
# AIC
\(\textit{R in Action}\)第\(202\)页讲完 anova() 函数就讲如何使用\(\text{Akaike Information Criterion (AIC)}\)来比较两个模型,以下是原文:
\(\text{The Akaike Information Criterion (AIC) provides another method for comparing models. The index takes into account a model’s statistical fit and the number of parameters needed to achieve this fit. Models with smaller AIC values—indicating adequate fit with fewer parameters—are preferred. The criterion is provided by the AIC() function (see the following listing).}\)
更重要的是, anova() 函数对比模型时要求这几个模型是嵌套模型,而 AIC() 函数没有这个要求。