我很难创建一个循环来识别列中缺少的值。我使用这个循环将列添加到一个较小的数据集中,用鼠标进行填充,然后合并回来。我不能在我的函数中手动编写,因为输出数据将是基于区号的一个较小的子集,而且每个地区代码在不同的列中有不同的缺失值。
供参考:
library(mice)
ListingPricePrep<-function(Zip,dataset){
City<-subset.data.frame(dataset,dataset$ZipCode==Zip)
#Fault Area#
t1<-mice(City[,c(7,12:13,15:16,21:22,24:25,27:28,30:31)],m=1,method = "norm")
t2<-mice(City[,9:10])
df1<-mice::complete(t1)
df2<-mice::complete(t2)
City<-cbind.data.frame(City[,c(1:3,5,6,8,11,14,20,23,26,29)],df1,df2)
City$LPB<-ifelse(City$`Median Listing Price`>mean(City$`Median Listing Price`)+sd(City$`Median Listing Price`),1,0)
City$LPMMB<-ifelse(City$`Median Listing Price M/M`>0,1,0)
City$LPYYB<-ifelse(City$`Median Listing Price Y/Y`>0,1,0)
City$ALCMMB<-ifelse(City$`Active Listing Count M/M`>0,1,0)
City$ALCYYB<-ifelse(City$`Active Listing Count Y/Y`>0,1,0)
City$DOMMMB<-ifelse(City$`Days on Market M/M`>0,1,0)
City$DOMYYB<-ifelse(City$`Days on Market Y/Y`>0,1,0)
City$NLCMMB<-ifelse(City$`New Listing Count M/M`>0,1,0)
City$NLCYYB<-ifelse(City$`New Listing Count Y/Y`>0,1,0)
City$ALPMMB<-ifelse(City$`Avg Listing Price M/M`>0,1,0)
City$APLYYB<-ifelse(City$`Avg Listing Price Y/Y`>0,1,0)
City$TLCMMB<-ifelse(City$`Total Listing Count M/M`>0,1,0)
City$TLCYYB<-ifelse(City$`Total Listing Count Y/Y`>0,1,0)
City$MonthName<-month(City$Month)
fits <- list(normal = fitdistr(City$`Median Listing Price`, "normal"),
weibull = fitdistr(City$`Median Listing Price`, "weibull"),
lognormal= fitdistr(City$`Median Listing Price`,"lognormal"),
logistic= fitdistr(City$`Median Listing Price`,"logistic"),
cauchy= fitdistr(City$`Median Listing Price`,"cauchy"),
poisson= fitdistr(City$`Median Listing Price`,"poisson"),
t= fitdistr(City$`Median Listing Price`,"t")
)
print(sort(sapply(fits,function(i) i$loglik),decreasing = T))
return(City)}
一些输出将工作,因为它们在上面指定的列中有缺失的值,而另一些输出将在鼠标中返回: Error (City,c(7,12:13,15:16,21:22,24:25,27:28,30:31) )。
这对我来说是一个有趣的项目,我可以通过选择合适的城市来强迫它工作,但我想练习制作functional...functions。
到目前为止,我对下面的循环非常不熟悉:
for (i in 1:length(dataset)) for (j in ncol(dataset)){
dat<-names(dataset[is.na(dataset[i,j])==T])
}附注:可以随意评论关于清理代码或优化您认为合适的建议。每个人都有不同的风格。
编辑

我只想根据月号和区号的不同,把价格中间价Y/Y这样的东西计算出来,有时会丢失,有时不会。
发布于 2017-06-28 13:53:13
我注意到的是你的dat并没有改变。因此,即使这是可行的,它也只能保留最后的价值。试试这个library(data.table) dt <- as.data.table(dataset) dt[,lapply(.SD,function(x){sum(is.na(x))>0})] # this will give you which columns have NA dt[,is.na(dt),with=F]
发布于 2017-06-28 14:50:04
dt <- as.data.table(dataset)
d1<-data.frame(dt[,lapply(.SD,function(x){sum(is.na(x))>0})]) # this will give you which columns have NA
d2<-(which(d1[1,]==TRUE))
d3<-dataset[,d2]谢谢你@quant的启动想法。我将使用==False创建第二个子集,并将结果合并回一起。
https://stackoverflow.com/questions/44803830
复制相似问题