多选取值_R语言缺失值的处理——回归预测法
1?讀取數(shù)據(jù)。
library(foreign) #加載程序包
stu_data_na=read.spss(file="stu_data_na.sav",to.data.frame=TRUE)?
head(stu_data_na) #查看數(shù)據(jù)前幾行
2??查看數(shù)據(jù)集缺失情況。
dim(stu_data_na) #查看數(shù)據(jù)維度
sum(complete.cases(stu_data_na)) #查看完整數(shù)據(jù)條數(shù)
library(mice) #加載mice包
md.pattern(stu_data_na) #利用函數(shù)md.pattern查看數(shù)據(jù)缺失情況
結(jié)果中的1表示無缺失,0表示有缺失。可以看到stu_data_na數(shù)據(jù)集共有26條完整數(shù)據(jù),x1、x2兩個變量中,x1是無缺失數(shù)據(jù)的,x2有8個缺失值。
3??下面利用回歸預(yù)測方法插補變量x2的缺失值。首先,將x2完整和有缺失的數(shù)據(jù)分開。
stu_1=which(is.na(stu_data_na[,4])==TRUE) #返回stu_data_na中第4列為缺失的行,也就是x2為空的行
stu_data_com1=stu_data_na[-stu_1,] #選取x2不為空的行
head(stu_data_com1)
stu_data_fill1=stu_data_na[stu_1,]? #選取x2為空的行
head(stu_data_fill1)
4??建立x2、x1的回歸模型。
lm=lm(x2~x1,data=stu_data_com1) #其中x1為自變量,x2為因變量
summary(lm)
從結(jié)果中可以看出,回歸模型是顯著的。x1和x2具有一定的線性關(guān)系。因此利用回歸模型來填補缺失值是可行的。
5??stu_data_fill1[,4]=round(predict(lm,stu_data_fill1))? #將x2的缺失值用非缺失值的回歸模型預(yù)測結(jié)果來替代
stu_data_fill1 #查看已經(jīng)補全的數(shù)據(jù)
6??stu_data_new=rbind(stu_data_com1,stu_data_fill1)#將填補了缺失值的數(shù)據(jù)與完整數(shù)據(jù)合并得到最終的數(shù)據(jù)集。
head(stu_data_new) #查看新的數(shù)據(jù)集
dim(stu_data_new?)
缺失值插補完成。
總結(jié)
以上是生活随笔為你收集整理的多选取值_R语言缺失值的处理——回归预测法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中的 隐藏鼠标菜单_如何在鼠标右键菜单中
- 下一篇: python中的input函数怎么用_p