Why is R sorting my character vector incorrectly?

I have a bunch of character vectors of numbers like this one:

numbers_c <- c("8.76782130111354e-05", "0.1523", "0.4316", "6.80470451316959e-05","2.45", 
"5.29226369075514e-05", "6.123", "7.11446903389845e-05")

I want to sort them from biggest to smallest, so I use the built-in sort-function and get this:

> sort(numbers_c, decreasing = TRUE)
 [1] "8.76782130111354e-05" "7.11446903389845e-05" "6.80470451316959e-05"
 [4] "6.123"                "5.29226369075514e-05" "2.45"                
 [7] "0.4316"               "0.1523"  

It seems like the sort-function doesn't get that the numbers with "e-05" are very small. How can I make it understand that?

Upvotes: 0

Views: 288

Answers (1)

GKi
GKi

Reputation: 39667

You can convert the character to numeric and use order.

numbers_c[order(as.numeric(numbers_c), decreasing = TRUE)]
#[1] "6.123"                "2.45"                 "0.4316"              
#[4] "0.1523"               "8.76782130111354e-05" "7.11446903389845e-05"
#[7] "6.80470451316959e-05" "5.29226369075514e-05"

Upvotes: 1

Related Questions