[R] putting NAs at the end

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Thu Aug 14 11:20:20 CEST 2003


Hi Angel,
On 14-Aug-03 Angel wrote:
> Yes, I have. I am sorry if I am missing some very basic stuff, but both
> order and sort will not only put the NAs at the end (with na.last=TRUE)
> BUT also sort in ascending or descending order the rest of the
> elements and that is not what I want. And with order I would only get
> the z NAs at the end and not also the associated x and y coordinates.

This may not be the best way to do it, but it works and, I think, does
what you want (and, in particular, preserves the original row order
within the NA and non-NA blocks):

Setup: First, a matrix x:
> x
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 11.1 11.2 11.3 12.1 12.2 12.3 13.1 13.2 13.3  14.1  14.2  14.3
[2,] 21.1 21.2 21.3 22.1 22.2 22.3 23.1 23.2 23.3  24.1  24.2  24.3
[3,] 31.1 31.2 31.3 32.1 32.2 32.3 33.1 33.2 33.3  34.1  34.2  34.3
[4,] 41.1 41.2 41.3 42.1 42.2 42.3 43.1 43.2 43.3  44.1  44.2  44.3
[5,] 51.1 51.2 51.3 52.1 52.2 52.3 53.1 53.2 53.3  54.1  54.2  54.3
[6,] 61.1 61.2 61.3 62.1 62.2 62.3 63.1 63.2 63.3  64.1  64.2  64.3

Setup: Next, set some NAs:
> x1<-x;x1[2,3]<-NA;x1[2,9]<-NA;x1[5,6]<-NA;x1[5,12]<-NA;x1
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 11.1 11.2 11.3 12.1 12.2 12.3 13.1 13.2 13.3  14.1  14.2  14.3
[2,] 21.1 21.2   NA 22.1 22.2 22.3 23.1 23.2   NA  24.1  24.2  24.3
[3,] 31.1 31.2 31.3 32.1 32.2 32.3 33.1 33.2 33.3  34.1  34.2  34.3
[4,] 41.1 41.2 41.3 42.1 42.2 42.3 43.1 43.2 43.3  44.1  44.2  44.3
[5,] 51.1 51.2 51.3 52.1 52.2   NA 53.1 53.2 53.3  54.1  54.2    NA
[6,] 61.1 61.2 61.3 62.1 62.2 62.3 63.1 63.2 63.3  64.1  64.2  64.3

The work: Now you want rows 2 and 5 at the end (if I understand):
> icol<-c(3,6,9,12)
> iNA<-is.na(rowSums(x1[,icol]))
> x2<-x1[!iNA,]
> x3<-x1[iNA,]
> x4<-rbind(x2,x3);x4
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 11.1 11.2 11.3 12.1 12.2 12.3 13.1 13.2 13.3  14.1  14.2  14.3
[2,] 31.1 31.2 31.3 32.1 32.2 32.3 33.1 33.2 33.3  34.1  34.2  34.3
[3,] 41.1 41.2 41.3 42.1 42.2 42.3 43.1 43.2 43.3  44.1  44.2  44.3
[4,] 61.1 61.2 61.3 62.1 62.2 62.3 63.1 63.2 63.3  64.1  64.2  64.3
[5,] 21.1 21.2   NA 22.1 22.2 22.3 23.1 23.2   NA  24.1  24.2  24.3
[6,] 51.1 51.2 51.3 52.1 52.2   NA 53.1 53.2 53.3  54.1  54.2    NA

The above five lines of code could make a function for your task.
Is this OK?
Best wishes,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 167 1972
Date: 14-Aug-03                                       Time: 10:20:20
------------------------------ XFMail ------------------------------




More information about the R-help mailing list