Announcement

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

  • Loop for Updating FIPS Codes: Replace Values of Variables with the Values of the Same Variable in Different Observations

    I have longitudinal data with several string and numeric variables for the county and state FIPS codes. I'm harmonizing all the FIPS codes to 2010 FIPS codes for analysis. I'm trying to create a loop that will replace the county, state, and full FIPS variables with values of the same variable in a different county

    For example, I have a county with original FIPS code 02201 with the following variables

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str2 ostate int ocntyfips str3 ocntyfips_str float ostate_n str2 ostate_str str5 fips
    "AK" 201 "201" 2 "02" "02201"
    "AK" 201 "201" 2 "02" "02201"
    "AK" 201 "201" 2 "02" "02201"
    "AK" 201 "201" 2 "02" "02201"
    end
    but I would like it to look like this, updating the FIPS and associated variables to 02130

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str2 ostate int ocntyfips str3 ocntyfips_str float ostate_n str2 ostate_str str5 fips
    "AK" 130 "130" 2 "02" "02130"
    "AK" 130 "130" 2 "02" "02130"
    "AK" 130 "130" 2 "02" "02130"
    "AK" 130 "130" 2 "02" "02130"
    end

    There are a handful of counties to be replaced, and several variables that need updating, I'm trying to figure out some sort of nested loop rather than doing it manually. So basically a faster way to do the following:

    replace fips="02130" if fips=="02201"
    replace ocntyfips=130 if ocntyfips==201
    etc..

    replace fips="02105" if fips=="02232"
    etc..

    I'm thinking something as follows but this doesn't quite get it

    Code:
    local old "02201 02232 02130"
    
    local new "02130 02105 02201"
    
    foreach v of varlist fips ocntyfips ocntyfips_str {
        replace `v'=`v' if fips=="old"
        }
    Thanks in advance!

  • #2
    See if one of these work for you:

    Code:
    clear
    set obs 1000
    
    g a = rnormal(1,1)
    g b = rnormal(2,2)
    g c = rnormal(3,3)
    
    g d = runiform()>0.5
    g e = runiform()>0.5
    g f = runiform()>0.5
    
    
    local varlist1 a b c
    local varlist2 d e f
    
    local c = 1
    foreach var in `varlist1' {
        local met `: word `c' of `varlist2''
        qui summ `var' if `met'==1
        di "Mean `var' at `met'==1 " r(mean)
        local c = `c' + 1
    }
    
    foreach v in a b c {
          gettoken met varlist2 : varlist2
          tabstat `v' if `met' == 1
    }

    Comment

    Working...
    X