Jin
Jin

Reputation: 555

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

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)

Upvotes: 3

Views: 870

Answers (4)

tmfmnk
tmfmnk

Reputation: 39858

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)

Upvotes: 1

arg0naut91
arg0naut91

Reputation: 14764

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  

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388972

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  

Upvotes: 2

jay.sf
jay.sf

Reputation: 72758

Just order the vector using factor with appropriate levels=.

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

Upvotes: 1

Related Questions