[R] extracting columns with NA's

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Fri Sep 19 12:33:25 CEST 2003


antonio rodriguez wrote:
> Hi All,
> 
> How do I can delete from a matrix (or array) only those columns which have
> all their values set to NA?

  use 'apply' to sweep through columns using a little function that sees 
if all values in a column are NA:

eg: x:
 > x
           [,1]      [,2] [,3]      [,4] [,5]       [,6]      [,7]
[1,] 0.8548990        NA   NA 0.5548089   NA 0.63123175 0.1101337
[2,] 0.9593472 0.7681048   NA 0.3365029   NA 0.04580849        NA

 > x[,apply(x,2,function(col){!all(is.na(col))})]

           [,1]      [,2]      [,3]       [,4]      [,5]
[1,] 0.8548990        NA 0.5548089 0.63123175 0.1101337
[2,] 0.9593472 0.7681048 0.3365029 0.04580849        NA

I imagine solutions requiring fewer and fewer keystrokes will appear in 
R-help presently!

Baz




More information about the R-help mailing list