Announcement

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

  • 'not sorted': Generate variable by group

    Hello,

    I have a dataset such that my panel consists of country i industry j and year t. My main explanatory variable is x. I would like to generate a variable x_mean that is defined as the meanover the previous periods by country.

    I tried to do the following:

    xtset panelid year (where panelid has dimension ij)
    gen x_mean =.
    bysort country: replace x_mean = L1.x if year == 1962
    bysort country: replace x_mean = (L1.x + L2.x)/2 if year == 1963
    etc.

    However, I get the error message "not sorted r(5);"

    I already tried to first write "sort country" or "sort country year" or "sort country industry year". But I still get the same error message.

    Could anyone please help me with coding the mean over previous previous by country?

    Thank you!


  • #2
    Once you have xtset using by: as well is unnecessary and can even conflict with using time series operators.

    Code:
    replace x_mean = L1.x if year == 1962
    
    replace x_mean = (L1.x + L2.x)/2 if year == 1963

    Comment

    Working...
    X