R: problems with sort (NA)

6

I have a vector that I want to sort using sort but, in doing so, I do not see the missing values ( NA ). How to make? Thankful.

> x
 [1] "b" "c" "a" NA  NA  "b" "c" "a" NA  NA  "b" "c" "a"
> sort(x)
[1] "a" "a" "a" "b" "b" "b" "c" "c" "c"
    
asked by anonymous 22.12.2015 / 15:17

2 answers

6

Just do as follows, using na.last=FALSE for missing values to appear at the beginning, na.last=TRUE to appear at the end, na.last=NA is the default value of this parameter:

> x
 [1] "b" "c" "a" NA  NA  "b" "c" "a" NA  NA  "b" "c" "a"
> sort(x, na.last = FALSE)
 [1] NA  NA  NA  NA  "a" "a" "a" "b" "b" "b" "c" "c" "c"
> sort(x, na.last = TRUE)
 [1] "a" "a" "a" "b" "b" "b" "c" "c" "c" NA  NA  NA  NA 
> sort(x, na.last = NA)
[1] "a" "a" "a" "b" "b" "b" "c" "c" "c"
    
22.12.2015 / 15:22
3

If you use the order function, the default is na.last = T . So the following would work:

> x <- c("c", "a", NA, "b")
> x[order(x)]
[1] "a" "b" "c" NA 

Just like Alexander's answer, you can put the NA's in front using:

> x[order(x, na.last = F)]
[1] NA  "a" "b" "c"

I think @Alexandre's answer is better, this is just another way to do it!

    
22.12.2015 / 16:53