Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a character vector where elements contain letters and numbers in R?

Tags:

sorting

r

r-faq

I have a character array

cf <- c("V440","V457","V116","V327","V446","V108",          "V155","V217","V120","V51","V477") 

I would like to sort it in descending order so that I will have an output like this:

V51 V108 V116 V120 V155 V217 V327 V440 V446 V457 V477 

I have tried sort.list() like this

cf[sort.list(cf)] 

and got this answer:

[1] "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477" "V51"  

and also tried order() and got same result.

Can someone help me please

like image 973
rinzy kutex Avatar asked Jul 08 '13 16:07

rinzy kutex


2 Answers

Try mixedsort from the "gtools" package:

> # install.packages("gtools") ## Uncomment if not already installed > library(gtools) > mixedsort(cf)  [1] "V51"  "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477" 

If you don't want to use mixedsort (not sure why one wouldn't), and if your vector has a pretty consistent pattern (eg letters followed by numbers), you can also probably try something like this. (Note: Relatively untested.)

newvec <- c("V440", "V457", "V116", "V327", "V446", "V108", "V155",              "V217", "V120", "V51", "V477", "B22", "A10", "Z01")  newvec[order(gsub("([A-Z]+)([0-9]+)", "\\1", newvec),               as.numeric(gsub("([A-Z]+)([0-9]+)", "\\2", newvec)))] #  [1] "A10"  "B22"  "V51"  "V108" "V116" "V120" "V155" "V217" "V327" "V440" # [11] "V446" "V457" "V477" "Z01"  
like image 86
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 23 '22 20:09

A5C1D2H2I1M1N2O1R2T1


Plenty of right answers here, this is another way, just for fun.

cf[order(nchar(cf), cf)] # [1] "V51"  "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477" 
like image 32
Matthew Plourde Avatar answered Sep 21 '22 20:09

Matthew Plourde