繁体   English   中英

如何首先按字母然后按数字对字符向量进行排序?

[英]How to sort a character vector first by letter and then by number?

我有一个字符向量,其中包含以字母和数字开头的字符串:

sample.condition
[1] "1_t"   "2_t"   "3_t"   "4_t"   "5_t"   "6_t"   "7_t"   "GFP_t" "1_t"  
[10] "2_t"   "3_t"   "4_t"   "5_t"   "6_t"   "7_t"   "GFP_t"

最终排序的向量的第1个位置应包含“ GFP”元素:

sample.condition
[1] "GFP_t"   "GFP_t" "1_t"   "2_t"   "3_t"   "4_t"   "5_t"   "6_t"   "7_t"   "1_t"  
[10] "2_t"   "3_t"   "4_t"   "5_t"   "6_t"   "7_t"   

我尝试了几种排序参数,但无济于事。

查找不以数字开头的字符串。 创建一个逻辑索引:

idx <- grepl("^[^0-9]", sample.condition)

使用此索引进行子集设置和排序。 然后,合并两个排序的子集:

c(sort(sample.condition[idx]), sort(sample.condition[!idx]))

#  [1] "GFP_t" "GFP_t" "1_t"   "1_t"   "2_t"   "2_t"   "3_t"   "3_t"  
#  [9] "4_t"   "4_t"   "5_t"   "5_t"   "6_t"   "6_t"   "7_t"   "7_t"    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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