I would do this using sprintf
and strsplit
:
x <- c('11111-111-11', '11111-1111-1', '1111-1111-11')
y <- strsplit(x, '-')
myfun <- function(y) {
first <- sprintf('%05d', as.integer(y[1]))
second <- sprintf('%04d', as.integer(y[2]))
third <- sprintf('%02d', as.integer(y[3]))
paste(first, second, third, sep='-')
}
sapply(y, myfun)
# [1] "11111-0111-11" "11111-1111-01" "01111-1111-11"
You could also do this with fancy regular expressions or the gsubfn
package but that may be overkill!