Character addition in column rows

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

How do I make it work?

For help with your specific code, can you please turn it into a self-contained reproducible example?

In the meantime, if I'm understanding your goal properly, I think you can do it in one step with stringr::str_pad():

library("stringr")

x <- c(99, 999, 9999, 99999)

str_pad(x, width = 5, pad = "0")
#> [1] "00099" "00999" "09999" "99999"

Created on 2018-11-25 by the reprex package (v0.2.1)

4 Likes

That's exactly what I was trying to do.
Thank you very much.

1 Like

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"

Created on 2018-11-26 by the reprex package (v0.2.1)

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:

if (nchar(cnefe.rr$municipio == 2)) {

should be

if (nchar(cnefe.rr$municipio) == 2) {
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.