在R中循环列和行

时间:2017-06-28 13:25:43

标签: r loops r-mice

我在创建循环以识别列中的缺失值时遇到困难。我正在使用此循环将列添加到较小的数据集中,使用鼠标进行归档,然后合并回来。我无法在我的函数中手动编写,因为输出数据将是基于区域代码的较小子集,并且每个区域代码在不同列中具有不同的缺失值。

供参考:

    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)

}

某些输出将起作用,因为它们在上面的指定列中缺少值,而其他输出将返回:  小鼠出错(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])
    }

P.S。您可以随意评论有关清理代码或您认为合适的优化的建议。每个人都有不同的风格。

修改

Sample Data Picture

我只是想把中间价格Y / Y这样的东西归咎于有时缺失,有时候不会,这取决于月份和地区代码。

2 个答案:

答案 0 :(得分:1)

我注意到您的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]

答案 1 :(得分:1)

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创建第二个子集并将结果合并在一起。