Reputation: 195
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
Upvotes: 4
Views: 723
Reputation: 522561
For a base R approach, we can try using strsplit
on each input using the regex pattern (?<=[A-Z])(?=[0-9])
, which will target the split between the letter and numbers potions. Then, we can left pad the number with zeroes to a width of 4 and paste together the two portions.
x <- c("AB1", "AB2", "AB54")
output <- sapply(x, function(x) {
parts <- strsplit(x, "(?<=[A-Z])(?=[0-9])", perl=TRUE)[[1]]
paste0(parts[1], sprintf("%04d", as.numeric(parts[2])))
})
output
AB1 AB2 AB54
"AB0001" "AB0002" "AB0054"
Upvotes: 5
Reputation: 389235
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))
Upvotes: 5