Announcement

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

  • Updating a variable in a foreach loop

    Hello
    I have a set of variables, each of which represents one of the benefits from implementing a program. Let's say these variables are bnft_1 bnft_2 bnft_3 bnft_4. Each of these variables is coded 1 ("Yes") if a household receives that particular benefit from the program, and is a missing value (.) otherwise

    I would like to create a variable that counts the number of benefits a household receives from the program. I have tried using a loop concept that is applicable in Python but does not seem to apply in Stata. What I have done is as follows

    Code:
    gen ttl_benefits = 0
    
    foreach var in varlist bnft_1 bnft_2 bnft_3 bnft_4 {
    ttl_benefits == ttl_benefits + 1 if  `var'==1
    }
    This doesn't work, since Stata reads ttl_benefits as a command within the loop. I would like ttl_benefits to have a value 0 if a respondent received none of the benefits, 1 if they received only 1, and so on, up to 4.

    Any help on this would be greatly appreciated.
    Thanks

  • #2
    See

    Code:
    help replace
    for the immediate fix However,

    Code:
    egen ttl_benefits = rowtotal(bnft_*)
    would be a solution without a tacit loop.

    Comment


    • #3
      Thanks Nick! The replace command turned out to be just what I needed.

      Comment

      Working...
      X