简体   繁体   中英

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM