0

I am new to coding and I am learning the basics of R. I have a data set that I made in Excel. They are Zip codes; however, zip codes starting with 0 automatically eliminated when exporting. I am attempting to iterate through and add the 0 back.

My thoughts were, assuming that the zip codes w/o an initial zero are 4 characters long, I simply find the iterations that have length of 4 and then add a 0 to the front, but I am not getting the right answer.

zip<-c(61415, 19087, 63122, 3104, 1938)
zip<-as.character(zip)

>for(i in zip){
+
+if(nchar(i)==4){
+   paste0("0",i)
+   }
+  }

NULL

I should get:

"61415", "19087", "63122", "03104", "01938"

camille
  • 15,634
  • 17
  • 33
  • 53
Holytails
  • 67
  • 7

2 Answers2

0

It can be done by formatting the numeric vector with sprintf

sprintf("%05d", zip)
#[1] "61415" "19087" "63122" "03104" "01938"

Another option is str_pad

library(stringr)
str_pad(zip, pad = "0", width = 5)
#[1] "61415" "19087" "63122" "03104" "01938"

NOTE: Both the options doesn't require any loop or any conditional statements

data

zip <- c(61415, 19087, 63122, 3104, 1938)
Community
  • 1
  • 1
akrun
  • 789,025
  • 32
  • 460
  • 575
0

In the case "zip" is a string, you can also try:

ifelse(nchar(zip) != 5, paste0("0", zip), zip)

[1] "61415" "19087" "63122" "03104" "01938"

In the case "zip" is a numeric vector:

formatC(zip, width = 5, format = "d", flag = "0")
tmfmnk
  • 36,341
  • 4
  • 40
  • 53