I want to add 0's into the middle of a string until a certain length.
e.g.
AB1
AB2
AB54
Would become:
AB0001
AB0002
AB0054
Thanks
Using stringr::str_replace
extract the numbers from the string and use sprintf
to add 0's as prefix.
stringr::str_replace(df$V1, '\\d+', function(m) sprintf('%04s', m))
#[1] "AB0001" "AB0002" "AB0054"
Another way to write the same logic with str_pad
instead of sprintf
.
library(stringr)
str_replace(df$V1, '\\d+', function(m) str_pad(m, 4, pad = '0'))
data
df <- structure(list(V1 = c("AB1", "AB2", "AB54")),
class = "data.frame", row.names = c(NA, -3L))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With