Hello everybody.
I'm having trouble creating this loop.
I'm trying to add "000" to the rows with only 2 characters from the "municipio" column. If the line has 3 characters, it is to add "00". If it has 4 characters, it only adds "0".
I'm trying to leave the rows of the column "municipio" like this:
"00099"
"00999"
"09999"
My code is probably wrong
My code:
if (nchar(cnefe.rr$municipio == 2)) {
for (i in 1:length(cnefe.rr$municipio)){
cnefe.rr$municipio <- paste0("000", cnefe.rr$municipio)
}
if (nchar(cnefe.rr$municipio == 3)) {
for (i in 1:length(cnefe.rr$municipio)){
cnefe.rr$municipio <- paste0("00", cnefe.rr$municipio)
}
}
}
when the process is over I get this message.
Warning message:
In if (nchar(cnefe.rr$municipio == 2)) {:
the condition has length> 1 and only the first element will be used
For the sake of completeness, I should point out that you can also zero-pad with sprintf(), though it's pickier and less predictable than str_pad():
x <- c(99, 999, 9999, 99999)
# OK if you have numeric, integer-like values
sprintf("%05d", x)
#> [1] "00099" "00999" "09999" "99999"
# Zero-padding only works with strings on certain platforms :-o
sprintf("%05s", as.character(x))
#> [1] " 99" " 999" " 9999" "99999"
The solution by @jcblum is of course the right one. Just for the sake of completeness, the error message in your original post is caused by wrong placement of the closing parentesis: