Announcement

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

  • Generating lagged values in panel for a given group

    Dear Community,

    I have panel data on a quarterly basis for few different companies. I set up a panel. I have indicators for each company for every quarter in year named t. I wanted to generate lagged values for these indicators. I used a code:
    Code:
    bysort company: gen lag_indicator=L.indicator
    However I saw the error message: not sorted

    I sorted time and companies. But I got this error message again. I tried:
    Code:
    bysort company t: gen lag_indicator=indicator[_n-1]
    However I didn't get the values I wanted. Stata generated values denoted as missing values for lags

    Please help me. I got stuck with it

  • #2
    You need to tell by to sort by company and t, but then to group observations only using company.

    Code:
    bysort company (t): gen lag_indicator=L.indicator

    Comment


    • #3
      It works! Thank you for your kind help

      Comment


      • #4
        The reasoning here is that -- once you have tsset or xtset in terms of (here) company time -- then one and only one sort order is compatible with that namely

        Code:
        bysort company (time)
        In contrast

        Code:
        bysort company: 
        is subtly wrong, because it ignores the sorting on time too -- and

        Code:
        bysort company time: 
        would be more obviously wrong, as it divides the dataset into singleton groups,

        Fact is that once you have tsset or xtset, Stata doesn't need to be reminded of the right sort order, although it will complain if data aren't in that order.

        Code:
        . webuse grunfeld, clear
        
        . tsset
        
        Panel variable: company (strongly balanced)
         Time variable: year, 1935 to 1954
                 Delta: 1 year
        
        . gen Linvest = L.invest
        (10 missing values generated)
        
        . sort invest
        
        . gen L2invest = L2.invest
        not sorted
        r(5);
        
        . tsset
        
        Panel variable: company (strongly balanced)
         Time variable: year, 1935 to 1954
                 Delta: 1 year
        
        . gen L2invest = L2.invest
        (20 missing values generated)
        
        .
        Note that tsset or xtset by itself restores the right sort order as a side-effect, provided that it has been previously declared.




        Comment


        • #5
          Thank you Nick for your comprehensive explanation. It helped me a lot with understanding

          Comment

          Working...
          X