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

From: Ted Harding <Ted.Harding_at_manchester.ac.uk>
Date: Thu, 14 Feb 2008 13:14:25 +0000 (GMT)


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 ------------------------------

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 14 Feb 2008 - 13:17:38 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 14 Feb 2008 - 14:00:14 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive