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)
}
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 |
+--------------------+
id(3) you are usingsum()which gives a cumulative or running sum. not a total.