Announcement

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

  • Problem with a loop- calculating averages for the range of variables

    Dear Community,

    I want to create a loop, calculating averages for few variables, so that my code would be shorter and it would save me some time. I have 6 indicators ind1 till ind6. I want to calculate yearly averages for them. I typed the code:
    Code:
    forvalues i=1(1)6{
    foreach x of varlist ind1-ind6{
    egen mean_ind`i'_year=mean(`x'), by(year)
    }
    }
    I saw variablr mean_ind1_year already defined. It is bizzare to me since I didn't define the variable.

  • #2
    You need to read the forum as well as write to it!

    This problem was explained only yesterday.

    See https://www.statalist.org/forums/for...le-layer-loops

    You need one loop, not a nested loop. Then the bizarre problem disappears.

    Code:
     
     forvalues i=1/6 {      egen mean_ind`i'_year=mean(ind`i'), by(year)  }

    Comment


    • #3
      I don't read the forum. Actually, I search first in the forum when struggling with something. But I will take your advice.
      The problem is solved. Thank you for helping me!

      Comment

      Working...
      X