R语言 如何对一个包含许多数字串的向量进行升序排序?

ztyzrc3y  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(109)

我有一个名字列表,我想按最后一个数字升序排序。

[1] "W2345_S-001-R1_1.csv"     "W2346_S-001-R1_10.csv"    

[3] "W2347_S-001-R1_2.csv"     "W2348_S-001-R1_9.csv"    

[5] "W2345_S-001-R2_1.csv"     "W2346_S-001-R2_10.csv" 

[7] "W2347_S-001-R2_2.csv"     "W2348_S-001-R2_9.csv"

我想先按R1再按R2排列它们。在R1或R2中,应该按1、2、9、10排列。因此,输出应为

1] "W2345_S-001-R1_1.csv"     "W2346_S-001-R1_2.csv"    

[3] "W2347_S-001-R1_9.csv"     "W2348_S-001-R1_10.csv"    

[5] "W2345_S-001-R2_1.csv"     "W2346_S-001-R2_2.csv" 

[7] "W2347_S-001-R2_9.csv"     "W2348_S-001-R2_10.csv"
wgx48brx

wgx48brx1#

在您的情况下,应该将字符串缩短为要排序的数字部分:第一组数字不是您要排序的起始数字。在这种情况下,请使用gsubstr_ordergtools::mixedorder的作用相同)正确排序:

library(stringr)
v[str_order(gsub("W.*1-","", v), numeric = TRUE)]

#[1] "W2345_S-001-R1_1.csv"  "W2347_S-001-R1_2.csv"  "W2348_S-001-R1_9.csv"  "W2346_S-001-R1_10.csv"
#[5] "W2345_S-001-R2_1.csv"  "W2347_S-001-R2_2.csv"  "W2348_S-001-R2_9.csv"  "W2346_S-001-R2_10.csv"
  • 正则表达式解释 *:基本上,"W.*1-"匹配任何以W开始,以1-结束,并且在.*之间有一个或多个字符的子字符串。2许多不同的正则表达式都可以在这里工作,所以这只是一种可能性。
d8tt03nd

d8tt03nd2#

为了好玩的R基溶液,

d1 <- data.frame(v1 = as.numeric(gsub('^.*-R([0-9]+)_([0-9]+).csv', '\\1', x)), 
                 v2 = as.numeric(gsub('^.*-R([0-9]+)_([0-9]+).csv', '\\2', x)))
x[order(d1$v1, d1$v2)]

[1] "W2345_S-001-R1_1.csv"  "W2347_S-001-R1_2.csv"  "W2348_S-001-R1_9.csv"  "W2346_S-001-R1_10.csv" "W2345_S-001-R2_1.csv"  "W2347_S-001-R2_2.csv" 
[7] "W2348_S-001-R2_9.csv"  "W2346_S-001-R2_10.csv"
    • 数据**
dput(x)
c("W2345_S-001-R1_1.csv", "W2346_S-001-R1_10.csv", "W2347_S-001-R1_2.csv", 
"W2348_S-001-R1_9.csv", "W2345_S-001-R2_1.csv", "W2346_S-001-R2_10.csv", 
"W2347_S-001-R2_2.csv", "W2348_S-001-R2_9.csv")

相关问题