![3e199161ab40bede11997002c9395882.png](https://i-blog.csdnimg.cn/blog_migrate/ec6dc0b9419c33ff9df191331a026473.jpeg)
本文通过一个案例把R语言回归分析中常用的知识点串起来,欢迎关注交流学习(添加微信公众号:素言素语Sue)
从Kaggle上获得了2019年全球156个国家幸福指数数据集(World Happiness Report,数据源:https://www.kaggle.com/PromptCloudHQ/world-happiness-report-2019)
各数据列分别为:
l Overall rank (整体排名)
l Country or region(国家或地区)
l Score(幸福值得分)
l GDP per capita(人均GDP)
l Social support(社会支持)
l Healthy life expectancy(健康寿命预期)
l Freedom to make life choices(自由选择的程度)
l Generosity(慷慨度)
l Perceptions of corruption(对腐败的认知度)
Score值越大,意味着幸福指数越高。我们想通过多元线性回归模型来看,幸福指数受到哪些指标的影响以及影响程度大小。
接下来内容主要包括四个方面:
1. 数据预处理
2. 建立模型-模型诊断-调整改进
3. 模型解释
4. 模型预测及效果评估
1.数据预处理
打开数据文件,查看数据集基本情况,本数据集共156条,9列数据,大部分为number类型。
data_raw<-read.csv(file.choose())
str(data_raw)
##输出结果:
'data.frame': 156 obs. of 9 variables:
$ Overall.rank : int 1 2 3 4 5 6 7 8 9 10 ...
$ Country.or.region : Factor w/ 156 levels "Afghanistan",..: 44 37 106 58 99 134 133 100 24 7 ...
$ Score : num 7.77 7.6 7.55 7.49 7.49 ...
$ GDP.per.capita : num 1.34 1.38 1.49 1.38 1.4 ...
$ Social.support : num 1.59 1.57 1.58 1.62 1.52 ...
$ Healthy.life.expectancy : num 0.986 0.996 1.028 1.026 0.999 ...
$ Freedom.to.make.life.choices: num 0.596 0.592 0.603 0.591 0.557 0.572 0.574 0.585 0.584 0.532 ...
$ Generosity : num 0.153 0.252 0.271 0.354 0.322 0.263 0.267 0.33 0.285 0.244 ...
$ Perceptions.of.corruption : num 0.393 0.41 0.341 0.118 0.298 0.343 0.373 0.38 0.308 0.226 ...
源数据集各列的列名太长了,先重新定义一下列名,方便后续使用。
colnames(data_raw)<-c("Rank","Country","Score","GDP.per","Social.support","Lift.expect","Freedom","Generosity","Perception")
查看缺失值,这个数据集比较规范和完整,各列没有缺失值。(如果有缺失值的话,需要根据情况填充或删除。一种典型的填充方法是用现有的平均值,中位数或模式代替缺失值)
sapply(data_raw, function(x) sum(is.na(x)))
选取需要的数据子集,这里我们只需要看幸福指数Score及其6个潜在影响因素。
data<-data_raw[3:9]
接下来看看这些变量之间的相关情况及变量自身的分布情况,可使用方阵散点图(scatterplotMatrix)。在此之前,需要加载car包。
需要说明一下,正常情况下通过install.packages("car") 语句加载即可,不过我在加载时出现了加载失败的情况,因此直接通过填入car包url链接地址的方式加载。
p_url<-"https://cran.r-project.org/bin/windows/contrib/4.1/carData_3.0-3.zip"
install.packages(p_url,repos=NULL,type="source")
library(car)
scatterplotMatrix(data,smoother=F)