Announcement

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

  • Creating rates using foreach

    I have a range of variables for counts of diagnoses each beginning "cat_" and another variable "population"

    I would like to create a new variable of the incidence e.g. "inc_cat_cardio"

    I can do this using:
    Code:
    gen inc_cat_cardio = cat_cardio / population
    However if I do:

    Code:
    foreach cat of var cat* {
    gen inc_`var' =  `var' / population
    }
    I get the following error: "/population invalid name"

    Help suggests that this is a typo but I have checked this and am using exactly the same spelling with and without foreach

    Can anybody advise on what I am doing wrong?

    Thanks

  • #2
    Your loop is the wrong way round. Your declared macro within the loop is cat not var, so Stata can only replace a reference to var with an empty string, hence the problem report which is that / population makes no sense as a name which is one of several possibilities after the equals sign.

    You need
    Code:
    foreach cat of var cat* {    
        gen inc_`cat' =  `cat' / population
    }
    or if you prefer

    Code:
    foreach var of var cat* {      
        gen inc_`var' = `var' / population  
    }

    Comment


    • #3
      Ah thanks. Sorry for the stupid question!

      Comment

      Working...
      X