如何使用 R 中的 stringr 将一位数字替换为两位数字

How to replace one digit numbers by two digits numbers using stringr in R

我想用 s01_s02_ 替换列 x s1_s2_s9_s10_ 的值, s09_s10_。我可以轻松地针对每种情况(例如 s1_)执行此操作,但并非针对所有情况(我的正则表达式知识很短)。 我怎样才能在不重复自己的情况下完成所有这些替换?

library(tidyverse)

df <- tibble( x = c('s1_', 's2_', 's9_', 's10_'))

pattern <- 's1_'  
replacement <-  's01_'  
stringr::str_replace(df$x, pattern, replacement)      
#> [1] "s01_" "s2_"  "s9_"  "s10_"
Created on 2020-11-12 by the reprex package (v0.3.0)

选项gsubfn

library(gsubfn)
df$x <- gsubfn("(\d+)", ~sprintf('%02d', as.numeric(x)), df$x)

类似于gsubfnstr_replace替换可以带一个函数

library(stringr)
str_replace(df$x, "\d+", function(x) sprintf('%02d', as.numeric(x)))
#[1] "s01_" "s02_" "s09_" "s10_"

dplyr

library(dplyr)
df %>%
    mutate(x = str_replace(x, "\d+", 
          purrr::as_mapper(~ sprintf('%02d', as.numeric(.x)))))