Announcement

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

  • Substring from variable to create geoid

    Hi,

    I have some trouble using -substring- and would like to ask for help.

    Below is the data sample. After making 'Tract_FIPS' into a string variable, I would like to subtract the first five digits to create the geo_id.

    For instance:
    Code:
    gen fips = string(Tract_FIPS, "%11.0f")
    gen geo_id = substring(fips,1,5)
    The problem is that AL is state '01' not '1' as shown in the data sample. If I follow my code, I would get 'geo_id = 10010' instead of '01001'.

    Is there a way I could add '0' in front of the first nine states?

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str2 State double Tract_FIPS
    "AL" 1001020200
    "AL" 1001021100
    "AL" 1003010600
    "AL" 1005950200
    "AL" 1005950400
    "AL" 1005950900
    "AL" 1011952100
    "AL" 1011952400
    "AL" 1013953000
    "AL" 1015000400
    "AL" 1017954400
    "AL" 1023956700
    "AL" 1025957800
    "AL" 1025958000
    "AL" 1033020100
    "AL" 1035960400
    "AL" 1035960600
    "AL" 1039962900
    "AL" 1041963400
    "AL" 1041963800
    "AL" 1041963900
    "AL" 1045020100
    "AL" 1045021000
    "AL" 1047996500
    "AL" 1047996900
    end
    Thank you so much!

  • #2

    Code:
    replace geo_id="0"+geo_id if real(geo_id)<100000
    hth,
    Jeph

    Comment


    • #3
      Hi Jeph,

      Thank you for your help! This adds '0' to all geo_ids, which is not the format I was looking for.
      For States with 2-digit codes (11,12...etc), my code works well. It's just the states with 1-digit codes and I want to add '0' in front.

      Comment


      • #4
        Code:
        gen geo_id = cond(substr(fips,1,2)=="10","0" + substr(fips,1,4),substr(fips,1,5))

        Comment


        • #5
          @ Ali,

          Thank you so much! I should have added more details for the 1-digit states.

          Comment

          Working...
          X