【问题标题】:Conditionally add character to a string有条件地向字符串添加字符
【发布时间】:2019-02-21 09:59:32
【问题描述】:

我正在尝试将 0 添加到字符串中,但仅限于某些条件。

我有一个像这样的文件名向量:

my.fl <- c("res_P1_R1.rds", "res_P2_R1.rds",
  "res_P1_R19.rds", "res_P2_R2.rds",
  "res_P10_R1.rds", "res_P10_R19.rds")

我想sort(my.fl) 以便文件名按PR 后面的数字排序,但目前排序结果如下:

 "res_P1_R1.rds"   "res_P1_R19.rds"  "res_P10_R1.rds"  "res_P10_R19.rds" "res_P2_R1.rds"   "res_P2_R2.rds" 

要解决这个问题,我需要在PR 之后添加0,但仅当以下数字范围为1-9 时,如果以下数字为&gt; 9,我什么都不想做。

结果应该如下:

"res_P01_R01.rds"   "res_P01_R19.rds"  "res_P10_R01.rds"  "res_P10_R19.rds" "res_P02_R01.rds"   "res_P02_R02.rds"

如果我对它进行排序,它会按预期排序,例如:

"res_P01_R01.rds" "res_P01_R19.rds" "res_P02_R01.rds" "res_P02_R02.rds" "res_P10_R01.rds" "res_P10_R19.rds"

我可以根据位置添加 0,但由于所需位置发生变化,我的解决方案仅适用于文件名的子集。我认为这将是一个常见问题,但我还没有设法找到关于 SO(或任何地方)的答案,非常感谢任何帮助。

【问题讨论】:

    标签: r string


    【解决方案1】:

    您应该可以只使用gtools 包中的mixedsort,这样就无需插入零。

    my.fl <- c("res_P1_R1.rds", "res_P2_R1.rds",
               "res_P1_R19.rds", "res_P2_R2.rds",
               "res_P10_R1.rds", "res_P10_R19.rds")
    
    library(gtools)
    
    mixedsort(my.fl)
    
    [1] "res_P1_R1.rds"   "res_P1_R19.rds"  "res_P2_R1.rds"   "res_P2_R2.rds"   "res_P10_R1.rds"  "res_P10_R19.rds"
    

    但如果你确实想插入零,你可以使用类似的东西:

    sort(gsub("(?<=\\D)(\\d{1})(?=\\D)", "0\\1", my.fl, perl = TRUE))
    
    [1] "res_P01_R01.rds" "res_P01_R19.rds" "res_P02_R01.rds" "res_P02_R02.rds" "res_P10_R01.rds" "res_P10_R19.rds"
    

    【讨论】:

      猜你喜欢
      • 2016-09-08
      • 2019-10-06
      • 2013-04-17
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多