Only sort the NA's at the end of a vector R

Viewed 361

Is it possible to sort a vector where the order for non-missing/non-NA values is maintained, but the NA's in the vector are sorted to the end?

For example could I turn this vector

vector<-c("Dog", "Cat", NA, "Tiger", NA, "Bear")

into this

vector<-c("Dog","Cat","Tiger","Bear", NA, NA)
4 Answers

You can remove NA value using na.omit and subset till the length of vector to get NA at end.

na.omit(vector)[1:length(vector)]
#[1] "Dog"   "Cat"   "Tiger" "Bear"  NA      NA  

Just order the vector using factor with appropriate levels=.

vector[order(factor(vector, levels=vector))]
# [1] "Dog"   "Cat"   "Tiger" "Bear"  NA      NA     

Another option could be:

sort(factor(vector, levels = vector), na.last = TRUE)

[1] Dog   Cat   Tiger Bear  <NA>  <NA> 

If some strings could be duplicated:

sort(factor(vector, levels = unique(vector)), na.last = TRUE)

Could also do:

vector[order(is.na(vector))]

# [1] "Dog"   "Cat"   "Tiger" "Bear"  NA      NA 

TRUE (equals 1) is higher than FALSE (equals 0), so NA's are moved to the end while all TRUE cases to the beginning, without taking into account the real strings.

Works as well with duplicated strings, for example:

vector <- c("Dog", "Dog", "Cat", NA, "Tiger", NA, "Bear")

vector[order(is.na(vector))]

# [1] "Dog"   "Dog"   "Cat"   "Tiger" "Bear"  NA      NA  
Related