Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting 0's into the middle of a string until certain length in R

Tags:

r

dplyr

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

like image 215
MLE Avatar asked Oct 19 '25 10:10

MLE


1 Answers

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))
like image 50
Ronak Shah Avatar answered Oct 22 '25 00:10

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!