Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to count observations in a panel prior to and after an event

    Hello,
    I have panel data in this format. I want to generate a counter that identifies the year of the event and then goes up for the following years and decreases for the prior years. The year in which the event happens can change, for example some firms it can be in 2005, for others it can be in 2006 and likewise.
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str3 firm int year byte flag
    "AAA" 2005 0
    "AAA" 2006 0
    "AAA" 2007 1
    "AAA" 2008 0
    "AAA" 2009 0
    "AAA" 2010 0
    "BBB" 2005 0
    "BBB" 2006 0
    "BBB" 2007 0
    "BBB" 2008 1
    "BBB" 2009 0
    "BBB" 2010 0
    end
    ------------------ copy up to and including the previous line ------------------

    I want to add another variable that is 0 for the year for which the flag is 1 and then decreases for prior years and increases for next years. Like below:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str3 firm int year byte(flag nthyear)
    "AAA" 2005 0 -2
    "AAA" 2006 0 -1
    "AAA" 2007 1  0
    "AAA" 2008 0  1
    "AAA" 2009 0  2
    "AAA" 2010 0  3
    "BBB" 2005 0 -3
    "BBB" 2006 0 -2
    "BBB" 2007 0 -1
    "BBB" 2008 1  0
    "BBB" 2009 0  1
    "BBB" 2010 0  2
    end

    Can someone suggest how to achieve this?

  • #2
    Code:
    by firm (year), sort: egen event_year = max(cond(flag, year, .))
    by firm (year): gen nthyear = year - event_year

    Comment


    • #3
      Ah, I appreciate the elegant solution in #2. I was working on a different approach, but I don't think I can do better than #2. Here is another way I guess!

      Code:
      gen sum = sum(flag)
      egen groups = group(firm sum)
      gen wanted = .
      bysort groups: replace wanted = _n - 1 if mod(groups, 2) == 0
      bysort groups: replace wanted = -(_N - (_n - 1)) if mod(groups, 2) != 0

      Comment


      • #4
        Code:
          
         by firm (year), sort: egen event_year = total(flag * year)
        is another trick -- if and only if flag is 1 just once and otherwise 0 for each panel.

        Comment


        • #5
          Thanks so much for the help. The solutions work perfectly.

          Comment

          Working...
          X