Lorenzo M
Lorenzo M

Reputation: 96

Ascending order of vector of numeric characters

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

Answers (2)

Kerry Jackson
Kerry Jackson

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

markus
markus

Reputation: 26343

You could try mixedsort from gtools

library(gtools)
mixedsort(x)
#[1] "-.5" "-.1" ".01" ".1"  "1"   "3"   "5" 

Upvotes: 0

Related Questions