[R] putting NAs at the end

Duncan Murdoch dmurdoch at pair.com
Thu Aug 14 14:20:53 CEST 2003


On Thu, 14 Aug 2003 09:47:49 +0200, you 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. 

Just use order on a version of the data where all non-NA values are
made the same.  For example,

> x <- c(3, 1, NA, 2, 4)
> o <- order(is.na(x))
> x[o]
[1]  3  1  2  4 NA

As recently pointed out by Brian Ripley, order() performs a "stable"
sort, so items that are tied stay in their original ordering.

Duncan Murdoch




More information about the R-help mailing list