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

Viewed 176

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

2 Answers
Related