我很難創建一個循環來識別列中的缺失值。我正在使用這個循環將列添加到一個較小的數據集中,用鼠標算出,然後合併回來。我不能在我的函數中手動編寫,因爲輸出數據將是基於區域代碼的較小子集,並且每個區域代碼在不同列中具有不同的缺失值。循環列和行中的R
參考:
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)
}
某些輸出將工作,因爲它們具有上述的指定列缺失值,和其他人將返回: 錯誤在小鼠(市[,C(7 ,12:13,15:16,21:22,24:25,27:28,30:31)],:: 找不到缺失值
這是一個有趣的項目,我可以強制它通過挑選合適的城市來工作,但我想練習製作功能有理...功能。
到目前爲止,我敢把基地與環如下圖所示:
for (i in 1:length(dataset)) for (j in ncol(dataset)){
dat<-names(dataset[is.na(dataset[i,j])==T])
}
附:隨意評論與清理代碼或您認爲合適的優化建議。每個人都有不同的風格。
編輯
我只是想推諉之類的平均期望價格Y/Y,它有時失蹤,有時沒有,取決於月份和區號。
請添加一個小例子數據集和想要的結果。 https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example –
請提供一個可重現的示例數據集。 – www