首页 > 解决方案 > 有条件地向字符串添加字符

问题描述

我正在尝试将 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)文件名按Pand后面的数字R排序,但就目前而言,排序结果如下:

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

要解决此问题,我需要在P和之后添加 0 R,但仅当以下数字范围为 时1-9,如果以下数字是> 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(或任何地方)的答案,非常感谢任何帮助。

标签: rstring

解决方案


您应该能够只使用mixedsortgtools中的内容,而无需插入零。

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"

推荐阅读