[R] Removing columns that are all NA from a matrix

(Ted Harding) Ted.Harding at manchester.ac.uk
Thu Feb 14 14:14:25 CET 2008


On 14-Feb-08 12:59:46, Martin Waller wrote:
> Hi,
> I guess this might be a FAQ or something, and there's
> probably a nice simple way to do it, but I can't think of it:
> 
> Given a matrix, I want to remove columns that are _entirely_
> filled with NAs (partial NAs are fine).
> 
> How please?
> 
> Thanks,
> Martin

It probably isn't a FAQ (it's a somewhat special question)
but the following illustrates one way to do it:

  M<-cbind(c(1,2,3,4),c(1,2,NA,4),c(NA,NA,NA,NA))
  M
##     [,1] [,2] [,3]
##[1,]    1    1   NA
##[2,]    2    2   NA
##[3,]    3   NA   NA
##[4,]    4    4   NA
  apply(M,2,function(x){!all(is.na(x))})
##[1]  TRUE  TRUE FALSE
  M[,apply(M,2,function(x){!all(is.na(x))})]
##     [,1] [,2]
##[1,]    1    1
##[2,]    2    2
##[3,]    3   NA
##[4,]    4    4

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 14-Feb-08                                       Time: 13:14:20
------------------------------ XFMail ------------------------------



More information about the R-help mailing list