r - 有条件地向字符串添加字符
问题描述
我正在尝试将 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)
文件名按P
and后面的数字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(或任何地方)的答案,非常感谢任何帮助。
解决方案
您应该能够只使用mixedsort
包gtools
中的内容,而无需插入零。
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"
推荐阅读
- flutter - How can I format a local mobile phone number to a international one?
- php - 如何阻止用户注册现有名称 laravel 5.5
- android - 不在 UI 线程上时如何请求权限?
- c# - 当标识字段位于两个单独的列中时,如何检索该特定记录的最新出现?
- typescript - 在条件下尊重 DRY 的清洁方式
- python - Python - 从文件中提取数据并插入到数组中包括“\n”。如何不包含它,以便我可以对文本进行排序并更改它?
- python - Python Bokeh 2.0.1 - UndoTool 的 JS 回调?
- php - Laravel With() 和 Where()
- reporting-services - SSRS 矩阵条件格式
- python - 如何计算 2 个分布图之间的距离?