Search code examples
rregexstringleading-zero

add leading 0 at a specific position in a string (R)


I have a list of strings of this kind:

f<-c("CC 982","RX 112","TR 002","FF 1328")

I need to add a leading 0, as with the str_pad function, at the beginning of the numerical portion, to get to this:

"CC 0982" "RX 0112" "TR 0002" "FF 1328"

For now, I have tried with sub

sub('(.{2})(.{1})(.{3})', "\\1\\20\\3", f) 

Close enough, but I don't want the leading 0 if the numerical string has 4 digits. What is the solution here? Thank you


Solution

  • We can split the string by space and then use sprintf to join the components

    d1 <- do.call(rbind, strsplit(f, "\\s+"))
    sprintf("%s %04d", d1[,1], as.numeric(d1[,2]))
    #[1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"
    

    Or with gsubfn/sprintf we get the expected output

    library(gsubfn)
    gsubfn("(\\d+)", ~sprintf("%04d", as.numeric(x)), f)
    #[1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"