(1)请分析MASS包里面的Boston数据集,想要研究该地区的房价价格中位数(medv)与其他影响因素的关系。 (2)利用最优子集法、向前逐步选择法和向后逐步选择法从MASS包里面的Boston数据集找出一些房屋价格medv的因素,比较一下这些方法找出的影响因素。(选择标准基于调整的R2,Cp和BIC准则,分别在这三个标准下分析) 根据如上两个问题,请用R语言代码解决
时间: 2024-03-02 10:54:19 浏览: 26
1. Boston数据集分析
首先加载MASS包和Boston数据集:
```r
library(MASS)
data(Boston)
```
查看数据集的基本信息:
```r
str(Boston)
summary(Boston)
```
可以看到数据集共有506个样本,14个变量,其中medv为因变量,其他13个变量为自变量。
接下来进行相关性分析:
```r
cor(Boston)
```
可以看到,medv与rm(房间数)的相关系数最大,为0.7,说明房间数对房价中位数的影响较大。
接下来进行线性回归分析:
```r
fit <- lm(medv ~ ., data = Boston)
summary(fit)
```
可以看到,变量indus、chas、age、dis、rad、tax和black的p值较大,说明它们与medv的关系不显著,可以考虑将它们从模型中删除。
2. 变量选择方法比较
首先加载leaps包:
```r
library(leaps)
```
接下来使用最优子集法:
```r
regfit.full <- regsubsets(medv ~ ., data = Boston)
summary(regfit.full)
```
可以看到,最优子集法选择了变量rm、nox、dis、rad、tax和ptratio。
接下来使用向前逐步选择法:
```r
regfit.fwd <- regsubsets(medv ~ ., data = Boston, method = "forward")
summary(regfit.fwd)
```
可以看到,向前逐步选择法选择了变量rm、nox、dis、rad、tax、ptratio和lstat。
接下来使用向后逐步选择法:
```r
regfit.bwd <- regsubsets(medv ~ ., data = Boston, method = "backward")
summary(regfit.bwd)
```
可以看到,向后逐步选择法选择了变量rm、nox、dis、rad、tax、ptratio和lstat。
根据调整的R2、Cp和BIC准则,选择最优模型:
```r
par(mfrow = c(2, 2))
plot(regfit.full, scale = "r2")
plot(regfit.full, scale = "Cp")
plot(regfit.full, scale = "bic")
reg.summary <- summary(regfit.full)
which.max(reg.summary$adjr2)
which.min(reg.summary$cp)
which.min(reg.summary$bic)
```
可以看到,调整的R2最大的模型包括变量rm、nox、dis、rad、tax和ptratio;Cp最小的模型包括变量rm、nox、dis、rad、tax、ptratio和lstat;BIC最小的模型包括变量rm、nox、dis、rad、tax、ptratio和lstat。因此,最优模型包括变量rm、nox、dis、rad、tax、ptratio和lstat。
相关推荐
![csv](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![csv](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)