Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Adding 0 to the front of incorrect zip codes

    Hello everyone.
    I am new to Stata so apologies if my error is a simple one, but my research so far has not been fruitful.
    I recently have been working with a dataset made of multiple csv's, which when they listed a zip code that started with 0, simply dropped the zero at the front and it was insheeted into Stata as a 4 character string. As I need to merge this data set with others by the zipcode, I need to add the 0's to the front. (geoid2 is the variable name for the zip codes, geoid2num is the generated numeric version of it used for the arithmetic check)

    Currently the code I've been working with to fix this is below:

    set trace on
    set traced 1

    destring geoid2, generate (geoid2num) force

    forvalues geoid2num = 1000/9015 {
    local temp : `geoid2'
    replace geoid2 : 0`geoid2'
    }

    The error i'm getting in stata is r(101) with the red text saying not allowed. Below is the relevant stata output:

    . forvalues geoid2num = 1000/9015 {
    2. local temp : `geoid2'
    3. replace geoid2 : 0`geoid2'
    4. }
    - forvalues geoid2num = 1000/9015 {
    - local temp : `geoid2'
    = local temp :
    not allowed
    replace geoid2 : 0`geoid2'
    }
    r(101);

    end of do-file

    This feels like a syntactical error on my part, any help will be greatly appreciated!

  • #2
    You can find the solution in a Stata FAQ: "Is there a way to put leading zeros in output?"
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float geoid2num
    1000
    9015
    end
    
    gen str5 zipcode = string(geoid2num,"%05.0f")

    Comment

    Working...
    X