我如何排序一个向量的名称包含许多字符串的数字在R中?

pxq42qpu  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(136)

我有一个名字列表,我想按R值升序排序。
[1] "W2345_S-001-R2-20D.datavalue.csv" "W2346_S-001-R4-20D.datavalue.csv"
[3] "W2347_S-001-R1-20D.datavalue.csv" "W2348_S-001-R3-20D.datavalue.csv"
[5] "W2349_S-001-R5-20D.datavalue.csv"
然而,mixedsort只给出了上面的结果(按W值排序),但我想按R1、R2、R3、R4、R5排列它们,忽略名称中包含的其他数字。
[1] "W2347_S-001-R1-20D.datavalue.csv" "W2345_S-001-R2-20D.datavalue.csv"
[3] "W2348_S-001-R3-20D.datavalue.csv" "W2346_S-001-R4-20D.datavalue.csv"
[5] "W2349_S-001-R5-20D.datavalue.csv"

dz6r00yl

dz6r00yl1#

list_of_names <- c("W2345_S-001-R2-20D_790.datavalue.csv",
                   "W2346_S-001-R4-20D_792.datavalue.csv",
                   "W2347_S-001-R1-20D_789.datavalue.csv",
                   "W2348_S-001-R3-20D_791.datavalue.csv",
                   "W2349_S-001-R5-20D_793.datavalue.csv")

library(stringr)

names_order <- order(as.numeric(str_match(list_of_names, "-R\\s*(.*?)\\s*-")[,2]))

list_of_names[names_order]

[1] "W2347_S-001-R1-20D_789.datavalue.csv" "W2345_S-001-R2-20D_790.datavalue.csv"
[3] "W2348_S-001-R3-20D_791.datavalue.csv" "W2346_S-001-R4-20D_792.datavalue.csv"
[5] "W2349_S-001-R5-20D_793.datavalue.csv"
6l7fqoea

6l7fqoea2#

# Your data
vals<-c( "W2345_S-001-R2-20D_790.datavalue.csv",
         "W2346_S-001-R4-20D_792.datavalue.csv",
         "W2347_S-001-R1-20D_789.datavalue.csv",
         "W2348_S-001-R3-20D_791.datavalue.csv",
         "W2349_S-001-R5-20D_793.datavalue.csv")

library(stringr)

vals_df<-data.frame(vals,
           position=str_extract(vals,"(?<=R)\\d{1}")|>
                 as.numeric())

vals_df[order(vals_df$position),]$vals

[1] "W2347_S-001-R1-20D_789.datavalue.csv" "W2345_S-001-R2-20D_790.datavalue.csv"
[3] "W2348_S-001-R3-20D_791.datavalue.csv" "W2346_S-001-R4-20D_792.datavalue.csv"
[5] "W2349_S-001-R5-20D_793.datavalue.csv

相关问题