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

Viewed 342

I want to replace the values of column x s1_, s2_, s9_ and s10_ by s01_, s02_, s09_ and s10_. I can easily do it for each case (e.g. s1_) but not for all (my regex knowledge is short). How can I do all those replacements without repeating myself?

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)
1 Answers

An option with gsubfn

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

Similar to gsubfn, the str_replace replacement can take a function

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

Or with dplyr

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