Announcement

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

  • Creating a loop of resulting variables within a loop

    Dear Stata users,

    I am have two variables (ideally I want to do what follows for 5-10 variables): "rgdp_pc" and "exp_conc_ind" and I want to calculate the average for each of these variables by country between 2000 and 2002 (the data I have is a panel). On top of calculating the averages for each variable, I want to collect all the new generated variables in a global (called final) which I want to use later. However, when I am doing that the global that is created only accounts for the final generated variable which will be in that case "exp_conc_ind_avg". Below is the code I am using:

    // Create the global
    global xlist rgdp_pc exp_conc_ind

    // Create a loop
    foreach var of varlist $xlist {
    egen `var'_avg=mean(`var') if year>=2000 & year<=2002, by(country)
    global final `var'_avg
    }
    //

    Hence my question is the following: Is there a way, within the loop, to include all the generated variables in the global I call final?

    Many thanks in advance for your kind help.

    Best regards,
    Samer

  • #2
    Sorry, I just realized the title is wrong: It should be "Creating a global of all variables within a loop"

    Comment


    • #3
      Code:
      macro drop final xlist
      clear*
      input x y z
      1 2 3
      4 5 6
      end
      
      global xlist x y z
      foreach var of varlist $xlist {
          global final "$final `var'_avg "
          }
      disp "$final"

      Comment


      • #4
        Many thanks Scott, it worked

        Best,
        Samer

        Comment

        Working...
        X