R base function to sort vector of strings based on length

走远了吗. 提交于 2019-12-03 14:11:31

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?

Not in R base, but this splits the strings in numeric and character parts and sorts appropriately:

v <- c("00-04", "05-09", "10-14", "100-104", "105-109", "110-114", "15-19", "20-24")
library(gtools)
mixedsort(v)
#[1] "00-04"   "05-09"   "10-14"   "15-19"   "20-24"   "100-104" "105-109" "110-114"

You can always copy the code of the mixedorder function defined in the gtools package if you don't want to load/depend on it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!