My original data set has three variables:
year, country, quantity
In my code, I create other variables named after the values of the "country" variable (China, India, etc.). I would like to define these variables in a way so that I may ultimately be able to drop "quantity", "country", and duplicates and just have the total quantity for each country in the given year.
I tried to populate these variables with the sum of the "quantity" variable for each year and country. I know the problem is in the line with bysort (if country=="`lev'"), but I don't know how to fix it. I tried:
This creates something like:
I would like it to create something like this:
year, country, quantity
In my code, I create other variables named after the values of the "country" variable (China, India, etc.). I would like to define these variables in a way so that I may ultimately be able to drop "quantity", "country", and duplicates and just have the total quantity for each country in the given year.
I tried to populate these variables with the sum of the "quantity" variable for each year and country. I know the problem is in the line with bysort (if country=="`lev'"), but I don't know how to fix it. I tried:
Code:
levelsof country
foreach lev in `r(levels)' {
bysort country year: egen `lev' = total(quantity) if country=="`lev'"
}
| year | country | quantity | India | China | US |
| 2000 | India | 1 | 1 | . | . |
| 2001 | India | 2 | 5 | . | . |
| 2001 | India | 3 | 5 | . | . |
| 2000 | China | 4 | . | 4 | . |
| 2004 | China | 5 | . | 5 | . |
| 2007 | China | 6 | . | 6 | . |
| 2001 | US | 7 | . | . | 7 |
| 2006 | US | 8 | . | . | 8 |
I would like it to create something like this:
| year | country | quantity | India | China | US |
| 2000 | India | 1 | 1 | 4 | |
| 2001 | India | 2 | 5 | . | 7 |
| 2001 | India | 3 | 5 | . | 7 |
| 2000 | China | 4 | . | 4 | |
| 2004 | China | 5 | . | 5 | |
| 2007 | China | 6 | . | 6 | |
| 2001 | US | 7 | . | . | 7 |
| 2006 | US | 8 | . | . | 8 |


Comment