Search code examples
macrosstatisticsstatastata-macros

Using a growth formula for grouped observations


I have a dataset which is shown below:

clear

input year price growth id
2008 5  -0.444  1
2009 .  .       1
2010 7  -0.222  1   
2011 9   0      1
2011 8  -0.111  1
2012 9   0      1
2013 11  0.22   1 
2012 10  0      2      
2013 12  0.2    2
2013 .  .       2  
2014 13  0.3    2    
2015 17  0.7    2
2015 16  0.6    2    
end

I want to generate variable growth which is the growth of price. The growth formula is:

growth = price of second-year - price of base year / price of base year

The base year is always 2012.

How can I generate this growth variable for each group of observation (by id)?


Solution

  • The base price can be picked out directly by egen:

    bysort id: egen price_b = total(price * (year == 2012))
    generate wanted = (price - price_b) / price_b
    

    Notice that total is used along with the assumption that, for each id, you have only one observation with year = 2012.