I have this situation, but with much more information:
Barcode NM00000512 NM000522 NM00000513 NM000514
And I would like to insert two more zeros in the shorter Barcodes, like this:
Barcode NM00000512 NM00000522 NM00000513 NM00000514
I tried this df$Barcode <- gsub('NM000', "NM00000",df$Barcode)
but didn't work. Thanks
Other answers make assumptions about the number of zeros (that there should be five). I assume that there should be exactly two characters in the front. If that's not the case, you could modify it to split the string before the first numeric digit (or according to whatever different rule applies).
barcode <- c("NM00000512", "NM000522", "NM00000513", "NM000514") pad <- function(barcode) { x <- as.integer(substring(barcode, 3)) #extract numbers n <- max(nchar(barcode)) - 2 #desired length of number in string paste0(substring(barcode, 1, 2), #the two characters sprintf(paste0("%0", n, "i"), x) #pad with zeros ) } pad(barcode) #[1] "NM00000512" "NM00000522" "NM00000513" "NM00000514"