Announcement

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

  • Using foreach or forvalues to divide two variables

    Hello everyone,

    I am in desperate need so please forgive me for not reading over the rules on how to properly post lines of code/ data examples but I've been stuck on this problem for a while. I have a dataset that has variables named numerator_jun18_1...numerator_jun18_11 all the way through numerator_apr19_1...numerator_apr19_11 and the same set-up but for denominators. Im trying to do the following function:

    gen score_jun18_1 = numerator_jun18_1 / denominator_jun18_1

    for all 200+ variables and am trying to do so using a for loop to save myself the 200+ lines of code and possibility for human error.

    I tried the following (acknowledging that I would have to do this for at least each month/year combination)
    forvalues i=1/11{
    local suffix cond(`i'<10, "00`i'", "0`i'")
    gen score_jun18_`suffix' = numerator_jun18_`suffix' / denominator_jun18_`suffix'
    }


    but received the r(198) invalid name error code. Any help would be greatly appreciated

  • #2
    Place an equal sign between "suffix" and "cond" in the local command. Without it, the expression is not evaluated and your local macro suffix just contains the formula, not the result.
    Code:
    . forvalues i=1/11{
      2. local suffix cond(`i'<10, "00`i'", "0`i'")
      3. macro list _suffix
      4. }
    _suffix:        cond(1<10, "001", "01")
    _suffix:        cond(2<10, "002", "02")
    _suffix:        cond(3<10, "003", "03")
    _suffix:        cond(4<10, "004", "04")
    _suffix:        cond(5<10, "005", "05")
    _suffix:        cond(6<10, "006", "06")
    _suffix:        cond(7<10, "007", "07")
    _suffix:        cond(8<10, "008", "08")
    _suffix:        cond(9<10, "009", "09")
    _suffix:        cond(10<10, "0010", "010")
    _suffix:        cond(11<10, "0011", "011")
    
    . 
    . forvalues i=1/11{
      2. local suffix = cond(`i'<10, "00`i'", "0`i'")
      3. macro list _suffix
      4. }
    _suffix:        001
    _suffix:        002
    _suffix:        003
    _suffix:        004
    _suffix:        005
    _suffix:        006
    _suffix:        007
    _suffix:        008
    _suffix:        009
    _suffix:        010
    _suffix:        011

    Comment

    Working...
    X