如果列中的NA
值太多,我正在尝试删除大型数据集中的列。数据集中有1007个变量。我想出了以下代码,但我认为它不起作用。
> for(i in 1:1007){
+ if (length(which(is.na(train3[i])=="TRUE"))>1955) train3[i]<-NULL
+ else train3[i]<-train3[i]
+ }
Error in which(is.na(train3[i]) == "TRUE") :
error in evaluating the argument 'x' in selecting a method for function 'which': Error in `[.data.frame`(train3, i) : undefined columns selected
所以我试图消除超过1955个NA的列。有没有办法使这项工作?
答案 0 :(得分:2)
代码未经过测试,因为该问题未提供示例数据:
train3 <- train3[, sapply(train3, function(x) sum(is.na(x))<=1955)]
答案 1 :(得分:0)
我创建了一个较小的矩阵[100 X 1007],但你可以调整它:
#MAKE UP SOME SAMPLE DATA
d<-sample(c(c(1:10),c(5:9),rep(NA,times=8)),size=100700,replace=TRUE)
train3<-data.frame(matrix(d,nrow=100))
#GET THE NA COUNTS PER COLUMN
counts<-apply(train3,2,function(x)length(x[is.na(x)]))
#SELECT ALL COLUMNS WITH LESS THAN 35 NA's (modify to 1945)
train3[,names(counts[counts<35])]