To remove columns with missing values, use:
mydf <- mydf[!sapply(mydf, anyMissing)]
This has two advantages:
(1) anyMissing is a fast way to check for missing values.
It drops down to C code and checks the bit patterns there.
(2) Using mydf[j] instead of mydf[,j] avoids problems if you end up with
one column.
Tim Hesterberg
>Two nice answers - Sorry 4
>1)
>mydf <- mydf[,which(apply(mydf,2, function(x) is.element(NA,x))==F)]
>
>Be aware though that this will transform your data frame into a vector if only
>one column has no NA values.
>
>From: Sebastien Bihorel, PharmD, PhD
>
>2)
>If all your data (x) are numeric, then try
>
>y <- x[,!is.na(colSums(x))]
>
>From: Kenton D. Juhlin
>
>3)
>new.frame<-as.data.frame(lapply(DF, function(x) if(any(is.na(x))) NULL else x))
>
>where DF is the name of your data.frame.
>David L Lorenz
>
>4)
>
>x[, colSums(is.na(x))==0]
>
>
>
>and to ensure that you still get a data frame when only one column would be
>left, use
>
>
>
>x[, colSums(is.na(x))==0, drop=F]
>
>Andreas Krause
>
>
>
>
>All worked nicely Thanks
|