R 有条件地向字符串中添加字符

R 有条件地向字符串中添加字符,r,string,R,String,我试图将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") 要解决此问题,我需要在p和R之后添加0,但仅当以下数字在1-9之间时,如果以下数字是>9,我不想做任何事情 结果如下: "res_P01_R01.rds" "res_P0

我试图将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")
要解决此问题,我需要在
p
R
之后添加0,但仅当以下数字在
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,但由于所需位置发生更改,因此我的解决方案仅适用于文件名的子集。我认为这是一个常见的问题,但我还没有找到答案,因此(或任何地方),非常感谢任何帮助。

您应该能够从
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"

my.fl您应该能够从
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"
my.fl
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"