Reputation: 555
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
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
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
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
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