我有一系列我想要标准化的列名.
names <- c("apple", "banana", "orange", "apple1", "apple2", "apple10", "apple11", "banana2", "banana12")
我希望任何具有一位数字的东西都用零填充,所以
apple banana orange apple01 apple02 apple10 apple11 banana02 ...
我一直在努力使用 stringr
strdouble <- str_detect(names, "[0-9]{2}") strsingle <- str_detect(names, "[0-9]") str_detect(names[strsingle & !strdouble])
但无法弄清楚如何有选择地替换/预先...
你可以使用sub("([a-z])([0-9])$","\\10\\2",names)
:
[1] "apple" "banana" "orange" "apple01" "apple02" "apple10" "apple11" "banana02" [9] "banana12"
它只更改字母后面有一个数字的名称($
字符串的结尾).
该\\1
选择在第一块()
:字母.然后它将前导0,然后是第二个块放入()
:数字.
这是一个使用负前瞻和后置断言来识别单个数字的选项.
gsub('(?