Hi All, How do I can delete from a matrix (or array) only those columns which have all their values set to NA? Cheers Antonio Rodriguez ---
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? > >Cheers > >Antonio Rodriguez >--- > >______________________________________________ >R-help at stat.math.ethz.ch mailing list >https://www.stat.math.ethz.ch/mailman/listinfo/r-help > >Try: > x<-matrix(1:16,4,4) > x[col(x)>=row(x)]<-NA > x[,! apply(x,2,function(x) all(is.na(x))) ] [,1] [,2] [,3] [1,] NA NA NA [2,] 2 NA NA [3,] 3 7 NA [4,] 4 8 12 Peter Wolf
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
If I have understood what you mean, you can use the (surely non-optimal) code: #build a matrix .... A<-matrix(1:20,nrow=5) A[2,4]<-NA A[,3]<-rep(NA,nrow(A)) #count the missing value in each column fi<-apply(A,2,function(x)sum(is.na(x))) #exclude column(s) having a number of NA equal to nrow(A). Of course you can modify the "==" as well as "nrow(A)" A1<-A[!which(fi==nrow(A)),] Hope this help you best, vito ----- Original Message ----- From: antonio rodriguez <arv at ono.com> To: R-help <r-help at stat.math.ethz.ch> Sent: Friday, September 19, 2003 11:58 AM Subject: [R] extracting columns with NA's> Hi All, > > How do I can delete from a matrix (or array) only those columns which have > all their values set to NA? > > Cheers > > Antonio Rodriguez > --- > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://www.stat.math.ethz.ch/mailman/listinfo/r-help