1

I have a variable id and I want a sum of investment for each id.

I'm trying to write a loop but it's not correct.

 levelsof id2, local(levels)
 foreach l of local levels {
     gen totalgovtake = sum(Real_Gov_Take_MUSD)
 }
1
  • As @Cybernike showed you didn't need a loop. Errors in this code included: (1) second time around the loop, it will fail as the new variable already exists (2) nothing in the code implies separate operations for each id (3) you are using sum() which gives a cumulative or running sum. not a total. Commented Oct 27, 2020 at 23:08

1 Answer 1

1

You don't really need to use a loop here. I've created some mock data to illustrate the solution (please try and provide mock data next time you ask a question).

input id value
1 20
1 30
1 25
2 60
2 50
3 10
3 20
4 50
end

bysort id: egen total = sum(value)

list, sepby(id)

     +--------------------+
     | id   value   total |
     |--------------------|
  1. |  1      20      75 |
  2. |  1      30      75 |
  3. |  1      25      75 |
     |--------------------|
  4. |  2      60     110 |
  5. |  2      50     110 |
     |--------------------|
  6. |  3      10      30 |
  7. |  3      20      30 |
     |--------------------|
  8. |  4      50      50 |
     +--------------------+
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! It really helped
The egen function sum() still works fine but as from Stata 9 what is documented is the equivalent egen function total().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.