【发布时间】:2019-01-06 20:42:44
【问题描述】:
假设您有一个包含 9 列的数据框。您想要删除在 5:9 列中具有所有 NA 的案例。如果 1:4 列中有 NA,则根本不相关。
到目前为止,我已经找到了允许您删除在 5:9 的 any 列中具有 NA 的行的功能,但我特别需要仅删除那些具有 all 的行em> NA 在第 5:9 列中。
我编写了自己的函数来执行此操作,但由于我有 300k+ 行,所以速度很慢。我想知道有没有更有效的方法?这是我的代码:
remove.select.na<-function(x, cols){
nrm<-vector("numeric")
for (i in 1:nrow(x)){
if (sum(is.na(x[i,cols]))<length(cols)){
nrm<-c(nrm,i)
}
#Console output to track the progress
cat('\r',paste0('Checking row ',i,' of ',nrow(x),' (', format(round(i/nrow(x)*100,2), nsmall = 2),'%).'))
flush.console()
}
x<-x[nrm,]
rm(nrm)
return(x)
}
其中 x 是数据框,cols 是一个向量,其中包含应检查 NA 的列的名称。
【问题讨论】: