R基函数可根据长度对字符串向量进行排序 [英] R base function to sort vector of strings based on length

查看:125
本文介绍了R基函数可根据长度对字符串向量进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道R基本程序包中是否已有一个可以对字符串向量进行排序的函数,该函数考虑了每个元素的长度,当然也考虑了字典顺序. 例如,在对某些具有年龄段的向量进行 sort 调用之后,您将拥有:

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)

我想拥有:

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

推荐答案

仅使用order:

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

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

这是您要找的吗?

这篇关于R基函数可根据长度对字符串向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆