Reputation: 96
I have a vector of numbers of type character.
x = c("5","-.5","-.1",".01",".1","1","3")
Is there a quick and easy way to order this character vector using the numeric value of each character? I can't find a clean way to do this.
So for instance, I want a function
x <- characterOrder(x)
With output:
c("-.5","-.1",".01",".1","1","3", "5")
Thank you!
Upvotes: 1
Views: 128
Reputation: 1871
You can do this in base R using the order function and the as.numeric when you order it by the as.numeric value.
x = c("5","-.5","-.1",".01",".1","1","3")
x[order(as.numeric(x))]
[1] "-.5" "-.1" ".01" ".1" "1" "3" "5"
If you want this in a function:
characterOrder <- function(x) {
return(x[order(as.numeric(x))])
}
Upvotes: 3
Reputation: 26343
You could try mixedsort
from gtools
library(gtools)
mixedsort(x)
#[1] "-.5" "-.1" ".01" ".1" "1" "3" "5"
Upvotes: 0