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

时间:2013-12-03 13:20:09

标签: r sorting vector

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

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"

最终排序的矢量应该在第一个位置包含“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"   

我尝试了几种争论,但没有任何进展。

1 个答案:

答案 0 :(得分:3)

找到不用数字盯着的字符串。创建逻辑索引:

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"