Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R base function to sort vector of strings based on length

I was wondering if there is an already made function in R base package that can sort a vector of strings taking into consideration the length of each element and then of course the lexicographical order. For instance after a sort call on some vector holding age groups you would have:

v <- c("00-04", "05-09", "10-14", "100-104", "105-109", "110-114", "15-19", "20-24"..etc)

whereas I would like to have:

v <- c("00-04", "05-09", "10-14", "15-19", "20-24"..etc.. "100-104", "105-109", "110-114")
like image 212
Marius Avatar asked Mar 11 '14 12:03

Marius


1 Answers

Simply with order :

v[order(nchar(v), v)]

## [1] "00-04"   "05-09"   "10-14"   "15-19"   "20-24"   "100-104" "105-109" "110-114"

Is that what you're looking for?

like image 94
Victorp Avatar answered Sep 19 '22 19:09

Victorp