1iqv1g

Sometimes in research, we want to create time period variables such as the first and last years that the firm in on the data base. This is helpful not to only visualize but also to see if a specific event occurs between the first and last years of the firm.

Q: How do we create first and last year variables?

A: Using Compustat, the code is as follows.
**Sort by the firm identifier and time identifier (resulting in chronologic order)
sort gvkey fyear

**designate the first observation according to the firm
by gvkey: gen `var’_beg=`var’ if _n==1

**Fill the empty rows with the same first observation
by gvkey: replace `var’_beg=`var’_beg[_n-1] if `var’_beg==. & `var’_beg[_n-1]!=.

**Sort by the firm identifier and time identifier (resulting in reverse order)
gsort gvkey -`var’
by gvkey: gen `var’_end=`var’ if _n==1
by gvkey: replace `var’_end=`var’_end[_n-1] if `var’_end==. & `var’_beg[_n-1]!=.

Advertisements