按字母内部的数字排序字符串

时间:2018-03-03 13:25:34

标签: r sorting

我有字符串向量,如:

 > all.files
 [1] "./freq_1.txt"  "./freq_10.txt" "./freq_11.txt" "./freq_12.txt"
 [5] "./freq_13.txt" "./freq_14.txt" "./freq_15.txt" "./freq_16.txt"
 [9] "./freq_17.txt" "./freq_18.txt" "./freq_19.txt" "./freq_2.txt" 
 [13] "./freq_20.txt" "./freq_21.txt" "./freq_22.txt" "./freq_23.txt"
 [17] "./freq_24.txt" "./freq_25.txt" "./freq_26.txt" "./freq_27.txt"
 [21] "./freq_28.txt" "./freq_29.txt" "./freq_3.txt"  "./freq_30.txt"
 [25] "./freq_4.txt"  "./freq_5.txt"  "./freq_6.txt"  "./freq_7.txt" 
 [29] "./freq_8.txt"  "./freq_9.txt"

现在我该如何将此向量排序为

 "./freq_1.txt" "./freq_2.txt" "./freq_3.txt" ....

1 个答案:

答案 0 :(得分:1)

你可以这样做:

no <- gsub("[^0-9]", "", all.files) # remove everything except 0-9
no <- as.numeric(no)
all.files[order(no)]  # sort by numeric component